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

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

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

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

Essentially,the process that controls inputA will never get a chance to change it. Further, if theloop were corrected by using a wait statement in place of the while, an infinite loopwould still occur. Since the wait is level sensitive, once its condition becomes TRUE, itwill continue to execute unless stopped by a wait with a FALSE condition, event control, or delay statement within the loop.Substituting a wait statement in Example 4.7 would be correct only if the body ofthe loop contained either a delay, wait (FALSE), or event control. These would all stopsimulation of this process and give the process that controls inputA a chance tochange its value.References: while 3.3; delay control 3.1; event control 4.2Concurrent Processes121module endlessLoop(inputinputA);reg[15:0]count;alwaysbegincount = 0;while (inputA)count = count + 1; // wait for inputA to change to FALSE("This will never print if inputA is TRUE!");endendmoduleExample 4.7 An Endless Loop4.3.3 Comparison of Wait and Event Control StatementsIn essence, both the event and wait statements watch for a situation that is generatedby an external process.

The difference between the two is that the event control statement is edge-triggered whereas the wait is a level-sensitive statement.Thus the event control is appropriate for describing modules that include edgetriggering logic, such as flip flops. When active, the event statement must see achange occur before its statement is executed. We may write:@(posedge clock)statement;When control passes to this statement, if clock has the value one, the execution willstop until the next transition to one. That is, the event operator does not assume thatsince clock is one that a positive edge must have occurred.

Rather, it must see the positive edge before proceeding.The wait, being level-sensitive, only waits if its expression isReferences: while 3.3FALSE.122The Verilog Hardware Description Language4.4 A Concurrent Process ExampleThe Producer-Consumer example presented in section 4.3 illustrated how two processes could communicate and transfer information by waiting for appropriate levelson interprocess handshake lines.

In this section, we specify a simple synchronous busprotocol and develop a simulation model for it using the event control (@) constructs.The cycle-accurate style of description will be used.Figure 4.2 illustrates the synchronous bus protocol to be used in our example. Aclock signal is transmitted on the bus and is used to synchronize the actions of the busmaster and bus slave. A write bus cycle takes one full clock period and a read cycletakes two.

The type of bus cycle being performed is indicated by the rwLine bus line;a zero indicates a read and a one indicates a write.At the beginning of a write cycle the bus master drives the rwLine, addrLines, anddataLines lines and waits for the end of the clock cycle. At the end of the clock cycle,the values will have propagated down the bus to the slave. On the negative edge ofclock, the slave loads the dataLines into the memory location specified by theaddrLines lines.A read cycle takes two clock periods to complete. During the first, and continuingthrough the second, the bus master drives the rwLine and addrLines lines. Duringthe second clock period, the bus slave drives the data lines with the value read fromConcurrent Processes123memory at address addrLines.

On the negative edge of second clock cycle, the masterloads dataLines into an internal register.The x’ed areas in addrLines and dataLines show values changing at the clock edge.In our description, they change in zero time; the x’s in the figure necessarily take upphysical space on the horizontal axis.Although the bus protocol is simple, it will illustrate the cycle-accurate specification of a clock-synchronous system and bring together a number of modeling constructs illustrated in smaller examples.Example 4.8 is organized as one module containing four processes described usingalways and initial statements.

Three processes model the clock, the bus master, andthe bus slave. The fourth initializes the system and sets up a monitor to displaychanges in values. The wiggleBusLines task is used by the master to encapsulate theactions of the bus protocol, hiding the details from other possible actions of the master. The processes communicate through the global variables clock, rwLine,addressLines, and dataLines instead of through nets. (Example 6.10 extends thisexample to using nets between the master and slave.)The description begins by defining two constants of the system, READ andWRITE. These definitions will make the wiggleBusLines task call more readable.Within the sbus module, a parameter is defined.

Parameter tClock is one half of theclock period and is set to 20. At this point we can consider this to be default value forthe tClock. This value will be substituted when the parameter name is used. (Later inChapter 6, parameters will be discussed more fully and we will see that this genericvalue can be overridden at instantiation time.) Finally, the registers are defined.

Sincewe are only implementing 32 16-bit words in memory m, we have only definedaddressLines to be 5 bits wide.When simulation of the two always and two initial statements begins, they willstart executing in arbitrary order. The description must be written so that it will workcorrectly under any starting order.The first initial statement in the example performs three important functions.First, it loads memory m from an external file called “memory.data” using thememh system task. The operation of this task will be described later. Secondly, clockis initialized to 0; it is important to initialize values that are used to synchronize processes.

Finally, thestatement displays the values rwLine, dataLines,addressLines, andanytime any of the first three change.The first always statement in the description simply inverts clock every tClocktime units (which is 20 in this case). It waits for tClock time units before executing.Even if this always statement started executing first, it will not access the value ofclock until it is set to 0 by the initial statement described above. Thus, the time delayThe Verilog Hardware Description Language124`define READ 0`define WRITE 1module sbus;parametertClock = 20;regclock;reg[15:0]m[0:31]; //32 16-bit wordsreg [15:0] data;// registers names xLine model the bus lines using global registersregrwLine; //write = 1, read = 0reg [4:0]addressLines;reg [15:0] dataLines;initialbegin("memory.data", m);clock = 0;("rw=%d, data=%d, addr=%d at time %d",rwLine, dataLines, addressLines,endalways#tClock clock =!clock;initial // bus master endbegin#1wiggleBusLines (`READ, 2, data);wiggleBusLines (`READ, 3, data);data = 5;wiggleBusLines (`WRITE, 2, data);data = 7;wiggleBusLines (`WRITE, 3, data);wiggleBusLines (`READ, 2, data);wiggleBusLines (`READ, 3, data);end);Concurrent Processes125task wiggleBusLines(inputreadWrite,input [5:0] addr,inout [15:0] data);beginrwLine <= readWrite;if (readWrite) begin // write valueaddressLines <= addr;dataLines <= data;endelse begin//read valueaddressLines <= addr;@ (negedge clock);end@(negedge clock);if (~readWrite)data <= dataLines; // value returned during read cycleendendtaskalways // bus slave endbegin@(negedge clock);if (~rwLine) begin //readdataLines <= m[addressLines];@(negedge clock);endelse//writem[addressLines] <= dataLines;endendmoduleExample 4.8 Behavioral Description of a Synchronous Busorders the start of these two statements and insures that this always statement won’tbe complementing an unknown value.The bus master process calls the wiggleBusLines task with three parameters, indicating the type of cycle, the memory address, and the data.

The third parameter isdefined in the task to be an inout, and represents the data to be written during a writebus cycle, or the data read during a read cycle. The task is called six times by the master process, passing different values to it. The first task call will cause wiggleBusLinesto read from address 2 and return the read value in data. The third call will cause awrite of the value 5 into memory address 2.126The Verilog Hardware Description LanguageThe bus master is written assuming that clock has just fallen and a new bus cycle isbeginning. If the bus cycle is a WRITE, the then part of the if is executed, loadingaddressLines and dataLines with the values passed to the task.

The task then waitsfor the next negative edge of the clock (i.e. the end of the write cycle) before returningfrom the task. When that negative edge occurs, we know that the end of the WRITEcycle has occurred and, as we will see, the bus slave has loaded the value in dataLinesinto m at the address in addressLines. The #1 assures that all other always and initialblocks execute first.Let’s trace the action of the slave during the write cycle.

The bus slave processbegins by waiting for the negative edge of the clock. Remember that these models arewritten assuming that a negative clock edge has just occurred and that a bus cycles isjust beginning. Thus the “@(negedge clock)” statement waits until the end of thecycle just started, at which point it executes its if statement. Since we are tracing awrite cycle, the else part of the if is executed and the value in dataLines is copied intom as addressed by addressLines.

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

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

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

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