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

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

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

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

The sequential portion of Example 1.6 is the secondalways block. The rules are:The sensitivity list of the always block includes only the edges for the clock, resetand preset conditions.These are the only inputs that can cause a state change. For instance, if we aredescribing a D ftip ftop, a change on D will not change the ftip ftop state. So the Dinput is not included in the sensitivity list.Inside the always block, the reset and preset conditions are specified first. If a negative edge on reset was specified, then the if statement should be “if (~reset) …”. Ifa positive edge on reset was being waited for, the if statement should be “if(reset)…”.A condition on the clock is not specified within the begin…end block.

The assignment in the last else is assumed by the synthesis tool to be the next state.Any register assigned to in the sequential always block will be implemented usingftip ftops in the resulting synthesized circuit. Thus you cannot describe purelycombinational logic in the same always block where you describe sequential logic.You can write a combinational expression, but the result of that expression will beevaluated at a clock edge and loaded into a register. Look ahead to Example 1.7for an example of this.Non-blocking assignments (“<=”) are the assignment operator of choice whenspecifying the edge-sensitive behavior of a circuit.

The “< =” states that all thetransfers in the whole system that are specified to occur on the edge in the sensi-Verilog — A Tutorial Introduction19tivity list should occur concurrently. Although descriptions using the regular “=”will synthesize properly, they may not simulate properly. Since both simulationand synthesis are generally of importance, use “<=” in this situation.Although these rules may seem to be rather “picky,” they are necessary for synthesistools to infer that a ftip ftop is needed in the synthesized circuit, and then to infer howit should be connected.Finally, a note about the fsm module.

The use of the names clock and reset have nospecial meaning for a synthesis tool. We used these names here in the example forclarity; they could be named anything in the model. By using the form of specificationshown in Example 1.6, a synthesis tool can infer the need for a ftip ftop, and whatshould be connected to its D, clock, and reset inputs.1.3.3 Non-Blocking Assignment ("<=")The non-blocking assignment is used to synchronize assignment statements so thatthey all appear to happen at once — concurrently.

The non-blocking assignment isused with an edge as illustrated in module fsm. When the specified edge occurs, thenthe new values are loaded concurrently in all assignments that were waiting for thesignal’s edge. In contrast to the regular assignment (“=”), the right-hand sides of allassignments waiting for the signal’s edge are evaluated first, and then the left-handsides are assigned (updated). Think of this as all of these assignments happening concurrently — at the same time — independent of any blocking assignments anywherein the description. Indeed, when all of the ftip ftops in a large digital system areclocked from the same clock edge, this is what happens.

The non-blocking assignment models this behavior.Consider an alternate version of the fsm module of Example 1.6, shown here inExample 1.7. This time the Verilog is written almost directly from the logic diagramin Figure 1.4. We have modeled the current state ftip ftops as separately named registers, cS0 and cS1, and we have included the next state equations in the second,sequential always block. Modules fsm and fsmNB should synthesize to the samehardware.Consider how the second always block works. The block waits for either a positiveedge on clock or a negative edge on reset.

If the negative edge on reset occurs, thenboth cS0 and cS1 are set to 0. If the positive edge of clock occurs, the right-hand sidesof the two “<=” assignments are evaluated. Then all of the assignments are made tothe registers on the left-hand side. Thus& in” (the AND ofand in) and|in” (the OR ofand in) are both evaluated, and then the results are assigned to cS1and cS0 respectively.When looking at the description, you should think of the two statementsThe Verilog Hardware Description Language20cS1 <= in & cS0;cS0 <= in | cS1;as occurring at the same time (i.e., concurrently).

Think of the right-hand sides as theinputs to two ftip ftops, and that the change in cS1 and cS0 occur when the clock edgeoccurs. Realize that they occur concurrently. The cS1 on the left-hand side of the firstline is not the value cS1 used on the right-hand side of the second line. cS0 and cS1on the right-hand sides are the values before the clock edge. cS0 and cS1 on the lefthand sides are the values after the clock edge. These statements could have been written in either order with the same resulting values for cS0 and cS1 after the clock edge!module fsmNB(output reg out,inputin, clock, reset);regcS1, cS0;always@(cS1, cS0) // the combinational portionout = ~cS1 & cS0;always @(posedge clock, negedge reset) begin // the sequential portionif (~reset) begincS1 <= 0;cS0 <= 0;endelse begincS1<= in & cS0;cS0 <= in | cS1;endendendmoduleExample 1.7 Illustrating the Non-Blocking AssignmentThis example illustrates the functionality being specified with the non-blockingassignment.

Across a whole design there may be many always statements in manydifferent modules waiting on the same edge of the same signal. The powerful featureof the non-blocking assignment is that all of these right-hand side expressions will beevaluated before any of the left-hand side registers are updated. Thus, you do not needto worry about which value of cS1 is being used to calculate cS0. With the “< =” youknow it is the value before the clock edge.Tutorial: See the Tutorial Problems in Appendix A.4.Verilog — A Tutorial Introduction211.4 Module HierarchyLet’s begin building a larger examplethat includes more and varied components.

Figure 1.6 illustrates pictorially what our design looks like. In thissection we will detail each of themodules and their interconnection.The example consists of a board module which contains a clock module(m555), a four-bit counter (m16), andour binaryToESeg display driver fromsection 1.2.1.4.1 The CounterWe look first at the counter modulemodule m16definition shown in Example 1.8. Our(output reg [3:0] ctr = 1,counter has two ports: the 4-bit counter reginputclock);ister ctr, and a clock to increment thecounter.

The example declares that the interalways @(posedge clock)nal register ctr and its output port are 4-bitctr <= ctr + 1;vectors and provides an initial simulationendmodulevalue for ctr (1); when simulation begins, ctrwill be set to the constant value specified toExample 1.8 A 4-Bit Counterthe right of the “=”. The counter is modeledbehaviorally using an always block. The module waits for a positive edge on clock.When that occurs, ctr is incremented and the module waits for the next positive edgeon clock. Since the generation of the new counter value occurs on an edge of a signal,the non-blocking assignment operator (“<=”) is used.If ctr had not been initialized, its bits would always be unknown.

When the simulator tries to increment a register whose bits are unknown (x), the result is unknown.Thus, for simulation ctr must be initialized.1.4.2 A Clock for the SystemOur counter needs a clock to drive it. Example 1.9 defines an abstraction of a “555”timer chip called m555 and shows the waveform generated from simulating thedescription.The m555 module has an internal register (clock) which is also the output of themodule. At the start of a simulation, the output has the value x as illustrated by thegray area in the example’s timing diagram. In this example, we choose to initialize theThe Verilog Hardware Description Language22module m555(output reg clock);initial#5 clock =1;always#50 clock = ~ clock;endmoduleExample 1.9 A Clock For the Counterclock after 5 time units have passed. (The initialization of ctr in the aboveExample 1.8 occurs at simulation time 0.) The m555 is further modeled behaviorallywith an always statement which states that after 50 time units clock will be loadedwith its complement.

Since an always statement is essentially a “while (TRUE)” loop,after the first 50 time units have passed, the always statement will be scheduled toexecute and change clock’s value in another 50 time units; i.e., this time at time 100.Because clock will change value every 50 time units, we have created a clock with aperiod of 100 time units.We may want to specify the clock period with real time units.

The timescale compiler directive is used to specify the time units of any delay operator (#), and the precision to which time calculations will be rounded. If the compiler directive`timescale 1ns / 100pswas placed before a module definition, then all delay operators in that module and anymodule that followed it would be in units of nanoseconds and any time calculationswould be internally rounded to the nearest one hundred picoseconds.References: timescale 6.5.31.4.3 Tying the Whole Circuit TogetherWe have now defined the basic modules to be used in our system.

What remains isthe tying of these together to complete the design shown in Figure 1.6. Example 1.10ties together the module definitions in Examples 1.3, 1.8, and 1.9 by defining anothermodule (called board) that instantiates and interconnects these modules. This isshown graphically in Figure 1.7.Most of the statements in the board module definition have previously beendescribed, however there are a few details to point out. The module declaration of thecounter shows two ports, ctrand clock.Verilog — A Tutorial Introductionmodule board;wire[3:0]wire23count;clock, eSeg;m16counter(count, clock);m555clockGen (clock);binaryToESeg disp(eSeg, count[3], count[2], count[1], count[0]);initial"count=%d, eSeg=%d", count, eSeg);endmoduleExample 1.10 The Top-Level Module of the Countermodule m16(output reg [3:0] ctr = 1,inputclock);ctris a 4-bit output and clock is a 1-bit input.

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

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

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

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