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

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

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

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

Selecting a single bit is called a bit-select, andselecting several contiguous bits is known as a part-select. Examples of these include:reg [10:0] counter;rega;reg [2:0] b;reg [-5:7] ca = counter [7];b = counter [4:2];// bit seven of counter is loaded into a// bits 4, 3, 2 of counter are loaded into bIn a bit-select, the bit to be selected may be specified with an expression or by a literal. The bits selected in a part-select must be specified with constant expressions orliterals; the values may be positive or negative.E.2 MemoriesMemories are defined using the register declaration:331reg [10:0] lookUpTable [0:31];This declares a 32 word array named lookUpTable where each word consists of 11bits.

The memory is used in an expression, for example, as follows:lookUpTable [5] = 75;This loads the fifth word of lookUpTable with the value 75.Memories may be multidimensional; here two and three dimensional arrays aredeclared:reg [7:0]reg [9:0]twoDarray [15:0] [63:0];threeDarray [31:0] [31:0][43:0];If an 8-bit register a is also declared, then a legal procedural assignment would be:a = twoDarray[3][2];Part and bit selects can be applied to memories; the select is the last index, which isadded to the end of the access.

Thus, accessing bits 7 through 0 of threeDarray couldbe written as:a = threeDarray[21][4][40][7:0];Reading memory array elements outside the range of a dimension returns anunknown x. Writing to a memory array element outside the range of a dimension hasno effect.It is illegal to select more than one word from a memory — a whole dimensioncannot be read at one time.

However, some system functions, likearepassed a memory’s name without indicies.The formal syntax specification in the previous section covers both register andmemory declarations.E.3 Integers and TimesRegisters are used to model hardware. Sometimes though, it is useful to perform calculations for simulation purposes. For example, we may want to turn off monitoringafter a certain time has passed. If we use registers for this purpose, the operations onthem may be confused with actions of the actual hardware. Integer and time variablesprovide a means of describing calculations pertinent to the simulation.

They are provided for convenience and make the description more self documenting.332The Verilog Hardware Description LanguageAn integer declaration uses the integer keyword and specifies a list of variables. Thetime declaration is the same except for the time keyword:integerintegertimetimea, b;c [1:100];q, r;s [31:0];//two integers// an array of integers// two time variables// an array of timesAn integer is a general purpose 32-bit variable. Operations on it are assumed to betwo’s complement and the most significant bit indicates the sign.A time variable is a 64-bit variable typically used with thesystem function.FSystem Tasks andFunctionsIn this section we present some of the built in Verilog System Tasks and Functions.Our philosophy for this book is not to become a substitute for the simulator manual.Rather, we want to illustrate a few of the basic methods of displaying the results ofsimulation, and stopping the simulation.F.1 Display and Write TasksThere are two main tasks for printing information during a simulation:andThese two are the same except thatalways prints a newline characterat the end of its execution.

Examples of thetask were given throughout themain portion of the book. A few details will be given here.The typical form of the parameters to these tasks is("Some text %d and maybe some more: %h.", a, b);This statement would print the quoted string with the value of a substituted in for theformat control "%d", and b is substituted in for the format control "%h". The "%d"indicates that the value should be printed in a decimal base.

%h specifies hexadecimal.Allowable letters in the format control specification are:The Verilog Hardware Description Language334display in hexadecimaldisplay in decimaldisplay in octaldisplay in binarydisplay ASCII characterdisplay net signal strength (see Table 10.4).display hierarchical namedisplay stringh or Hd or Do or Ob or Bc or Cv or Vm or Ms or SUsing the construct "%0d" will print a decimal number without leading zeros orspaces. This may be used with h, d, and o also.Two adjacent commas („) will print a single space. Other special characters may beprinted with escape sequences:\n\t\\\"\dddis the new line characteris the tab characteris the \ characteris the " characteris the character specified in up to 3 octal digitsFor instance:("Hello world\n");will print the quoted string with two newline characters (remember,matically adds one at the end of its execution).auto-F.2 Continuous MonitoringThecommand is used to print information whenever there is a change inone or more specified values.

The monitor prints at the end of the current time so thatall changes at the current time will be reflected by the printout. The parameters forthetask are the same as for thetask.The command is:(parameters as used in thetask);Whenever thetask is called, it will print the values and set up the simulatorto print them anytime one of the parameters changes. Only onedisplay listmay be active at a time. If time is being printed as in the followingstatement, a change in simulation time will not trigger theto print.335("regA = ", regA);F.3 Strobed MonitoringThetask also uses the same parameter list format as thetask.

Unlikeit will print just before simulation time is about to advance. In this way,insures that all of the changes that were made at the current simulation timehave been made, and thus will be printed.F.4 File OutputTheandtasks have a version for writing to a file.They each require an extra parameter, called the file descriptor, as shown below:(descriptor, parameters as in the display command);(descriptor, parameters as in the write command);(descriptor, parameters as in the monitor command);(descriptor, parameters as in the strobe command);The descriptor is a 32-bit value returned from thefunction. The descriptormay be stored in a 32-bit reg.

Thefunction takes the form:("name of file");will return 0 if it was unable to open the file for writing. When finished writing to a file, it is closed with the function call:(descriptor);The descriptors are set up so that each bit of the descriptor indicates a differentchannel. Thus, multiple calls towill return a different bit set. The least significant bit indicates the “standard output” (typically a terminal) and need not be opened.By passing the OR of two or more descriptors to one of the printing commands, thesame message will be printed into all of the files (and standard output) indicated bythe ORed descriptors.The Verilog Hardware Description Language336F.5 Simulation Timeis a function that returns the current time as a 64-bit value.32-bit value.

The time may be printed, for instance, with theshown below:(will return acommand as"regA = ", regA);Note that the change of simulation time will not trigger theto print.F.6 Stop and FinishTheandtasks stop simulation. They differ in thatreturns controlback to the simulator’s command interpreter, whilereturns back to the hostoperating system.A parameter may be passed to these tasks with the following effects.If the forms with no parameter are used, then the default is the same as passing a 1to it.F.7 RandomThesystem function provides a random number mechanism, returning anew random number each time the function is called. The size of the returned value isthe same as an integer variable.

Typicalusages is illustrated below:337parameter SEED = 33;reg [31:0] vector;always @(posedge clock)vector =(SEED);F.8 Reading Data From Disk FilesTheandsystem tasks are used to load information stored indisk files into Verilog memories. The “b” version reads binary numbers and the “h”version reads hexadecimal numbers.The general syntax for the task call is:(“filename”, <memname>, <<start_addr> <,<finish_addr>>?>?);where:x is “b” or “h”<memname> specifies the Verilog identifier of the memory to be loaded.<start_addr> optionally specifies the starting address of the data. If none is specified, the left-hand address given in the memory declaration is used. If the<finish_addr> is specified, loading begins at the <start_addr> and continues to the<finish_addr>. Also see below for an alternate specification of the starting address.<finish_addr> is the last address to be written into.Addresses can be specified within the file as well.

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

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

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

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