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

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

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

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

This value is substitutedin the module instantiation for its parameter. Thus, by changing the parameter Widthin module sillyComputation to, say 23, then all of the module instantiations for thedatapath would be 23 bits wide. Parameterizing modules allows us to reuse a genericmodule definition in more places, making a description easier to write. If #(Width)had not been specified in the module instantiation statement, then the default value of8, specified in module register, would be used. The example also illustrates the use ofunsized constants. The constant 1 specification (given as 'b1 in the port list of adderinstance addI) specifies that regardless of the parameterized Width of the module,the value 1 will be input to the adder.

That is the least significant bit will be 1 with asmany 0s padded to the left as needed to fill out the parameterized width. This is alsogrue of unsized constants 'b0 and 'd10 in the compare module instantiations.Logic Synthesis632.7.5 Specifying the FSMNow that the datapath has been specified, a finite state machine is needed to evokethe register transfers in the order and under the conditions specified by the originalcomputation.

We first present a state transition diagram for this system and thendescribe the Verilog fsm module to implement it.The state transition diagram is shown in Figure 2.5 along with the specification forthe computation. The states marked “...” represent the computation before and afterthe portion of interest to us. Each state “bubble” indicates the FSM outputs that areto be asserted during that state; all others will be unasserted. The arrows indicate thenext state; a conditional expression beside an arrow indicates the condition in whichthat state transition is taken.

The diagram is shown as a Moore machine, where theoutputs are a function only of the current state. Finally, the states are labeled Athrough F for discussion purposes.Following through the computation and the state transition diagram, we see thatthe first action is to clear both the x and i registers in state A. This means that whilethe machine is in state A, xClear and iClear are asserted (low). Note though that theregisters i and x will not become zero until after the positive clock edge and we’re inthe next state (B). State B then asserts the load signals for x and i. The datapath inFigure 2.4 shows us what values are actually being loaded: x + y and i + 1 respectively.Thus, state B executes both the loop body and the loop update.

From state B the system goes to state C where there is no FSM output asserted. However, from state Cthere are three possible next states depending on whether we are staying in the loop(going to state B), exiting the loop and going to the then part of the conditional (stateD), or exiting the loop and going to the else part of the conditional (state E). Thenext state after D or E is state F, the rest of the computation.64The Verilog Hardware Description LanguageIt is useful to understand why state C is needed in this implementation of the system. After all, couldn’t the conditional transitions from state C have come from stateB where x and i are loaded? The answer is no. The timing diagram in Figure 2.6 illustrates the transitions between states A, B, and C.

During the time when the system isin state B, the asserted outputs of the finite state machine are xLoad and iLoad,meaning that the x and i registers are enabled to load from their inputs. But they willnot be loaded until the next clock edge, the same clock edge that will transit the finitestate machine into state C. Thus the values of i, on which the end of loop condition isbased, and x, on which the if-then-else condition is based, are not available for comparison until the system is in state C.

In the timing diagram, we see that since i is lessthan or equal to 10, the next state after C is B.It is interesting to note that in this implementation of the system, the exit condition of the for loop is not checked before entering the loop. However, given that wejust cleared i before entering the loop, it is not necessary to check that is less than orequal to 10. Further, with a different datapath, state C might not be necessary. Forinstance, the comparisons with i and x could be based on the input value to these registers, thus comparing with the future value.

Or the constants with which the comparisons are made could be changed. Of course, these are all at the discretion of thedesigner.Logic Synthesis65Now consider the Verilog model of the finite state machine for this system shownin Example 2.28. The machine’s inputs are the two conditions, x < 0 and i <= 10.Internal to the fsm module, they are called LT andrespectively.

Module fsmalso has a reset input and a clock (ck) input. The module outputs are the controlpoints on the registers (yLoad, yClear, xLoad, xClear, iLoad, iClear). Like our previous fsm examples, there are two always blocks, one for the sequential state change andthe other to implement the next state and output combinational logic. Registers aredeclared for all of the combinational outputs.Our state machine will only implement the states shown in the state transition diagram, even though there would be many more states in the rest of the computation.Thus, the width of the state register (cState) was chosen to be three bits. Further, thereset state is shown to be state 0 although in the full system it would be some otherstate. A very simple state assignment has been chosen, with state A encoded by 0, Bencoded by 1, and so on.The first always block is very similar to our previous state machine examples.

Ifreset is asserted, then the reset state is entered. Otherwise, the combinational valuenState is loaded into cState at the positive clock edge.The second always block implements the next state and output combinationallogic. The inputs to this combinational logic are the current state (cState) and fsminputs (LT andThe body of the always block is organized around the value ofcState. A case statement, essentially a multiway branch, is used to specify what is tohappen given each possible value of cState.

The value of the expression in parentheses, in this case cState, is compared to the values listed on each line. The line with thematching value is executed.If the current state changes to state A, then the value of cState is 0 given ourencoding. Thus, when this change occurs, the always block will execute, and the statement on the right side of the 3'b000: will execute. This statement specifies that all ofthe outputs are unasserted (1) except iClear and xClear, and the next state is 3'b001(which is state B). If the current state is B, then the second case item (3'b001) is executed, asserting iLoad and xLoad, and unasserting all of the other outputs. The nextstate from state B is C, encoded as 3'b010.

State C shows a more complex next statecalculation; the three if statements specify the possible next states from state C andthe conditions when each would be selected.The last case item specifies the defaultsituation. This is the statement that is executed if none of the other items match the value of cState.

For simulation purposes,you might want to have astatement to print out an error warning that you’vereached an illegal state. Theprints a message on the screen during simulation, acting much like a print statement in a programming language. This one displays the message “Oops, unknown state: %b” with the binary representation of cStatesubstituted for %b.66The Verilog Hardware Description LanguageTo make this always block a combinational synthesizable function, the default isrequired. Consider what happens if we didn’t have the default statement and the valueof cState was something other than one of the five values specified.

In this situation,the case statement would execute, but none of the specified actions would be executed. And thus, the outputs would not be assigned to. This breaks the combinationalsynthesis rule that states that every possible path through the always block mustassign to every combinational output. Thus, although it is optional to have the defaultcase for debugging a description through simulation, the default is required for thisalways block to synthesize to a combinational circuit.

Of course a default is notrequired for synthesis if all known value cases have been specified or cState wasassigned a value before the case statement.Consider now how the whole FSM-Datapath system works together. Assume thatthe current state is state C and the values of i and x are 1 and y respectively, as shownin the timing diagram of Figure 2.6. Assume further that the clock edge that causedthe system to enter state C has just happened and cState has been loaded with value3'b010 (the encoding for state C).

Not only has cState changed, but registers x and iwere also loaded as a result of coming from state B.In our description, several always blocks are were waiting for changes to cState, x,and i. These include the fsm’s combinational always block, the adders, and the compare modules. Because of the change to cState, x, and i, these always blocks are nowenabled to execute. The simulator will execute them, in arbitrary order. Indeed, thesimulator may execute some of them several times.

(Consider the situation where thefsm’s combinational always block executes first. Then after the compare modules execute, it will have to execute again.) Eventually, new values will be generated for theoutputs of the comparators. Changes in LT andin the fsm module will cause itscombinational always block to execute, generating a value for nState. At the next positive clock edge, this value will be loaded into cState and another state will be entered.References: case 3.4; number representation B.32.8 Summary on Logic SynthesisWe have seen that descriptions used for logic synthesis are very stylized and that someof the constructs are overloaded with semantic meaning for synthesis. In addition,there are several constructs that are not allowed in a synthesizable description.Because these can vary by vendor and version of the tool, we chose not to include atable of such constructs. Consult the user manual for the synthesis tool you are using.Table 2.1 summarizes some of the basic rules of using procedural statements todescribe combinational logic and how to infer sequential elements in a description.Logic Synthesis67module fsm(inputoutput regreg[2:0]LT,ck, reset,yLoad, yClear, xLoad, xClear, iLoad, iClear);cState, nState;always @(posedge ck, negedge reset)if (~reset)cState <= 0;elsecState <= nState;always @(cState, LT,case (cState)3'b00: begin//stateAyLoad = 1; yClear = 1; xLoad = 1; xClear = 0;iLoad = 1; iClear = 0; nState = 3'b001;end3'b001: begin// state ByLoad = 1; yClear = 1; xLoad = 0; xClear = 1;iLoad = 0; iClear = 1; nState = 3'b010;end3'b010: begin//state CyLoad = 1; yClear = 1; xLoad = 1; xClear = 1;iLoad = 1; iClear = 1;ifnState = 3'b001;if(~& LT) nState = 3'b011;if (~& ~LT) nState = 3'b100;end3'b011: begin//state DyLoad = 1; yClear = 0; xLoad = 1; xClear = 1;iLoad = 1; iClear = 1; nState = 3'b101;end3'b100: begin//state EyLoad = 1; yClear = 1; xLoad = 1; xClear = 0;iLoad = 1; iClear = 1; nState = 3'b101;enddefault: begin // required to satisfy combinational synthesis rulesyLoad = 1; yClear = 1; xLoad = 1; xClear = 1;iLoad = 1; iClear = 1; nState = 3'b000;("Oops, unknown state: %b", cState);endendcaseendmoduleExample 2.28 FSM For the DatapathThe Verilog Hardware Description Language682.9 Exercises2.12.22.32.42.52.62.7In section 2.2 on page 37, we state that a synthesis tool is capable, and possiblyconstrained, to implement the functionality using different gate primitives.Explain why it might be “constrained” to produce an alternate implementation.Alter the description of Example 2.7 so that there is no longer an inferred latch.When a is not one, b and c should be OR-d together to produce the output.Alter the description of Example 2.16.

Use a case statement to infer the latch.Why can’t while and forever loops be used to specify combinational hardware?Rewrite Example 2.21 as a Moore machine. An extra state will have to beadded.Rewrite Example 2.21 using a one-hot state encoding. Change the descriptionto be fully parameterized so that any state encoding may be used.Write a description for the FSM shown in Figure 2.7 with inputs Ain, Bin,Cin, clock, and reset, and output Y.A. A single always blockB.

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

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

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

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