Verilog Vectors and Arrays

Welcome back to my series covering mathematics and algorithms with FPGAs. In this part, we dig into vectors and arrays, including slicing, configurable widths, for loops, and bit and byte ordering. New to the series? Start with Numbers in Verilog .

Share your thoughts with @WillFlux on Mastodon or Twitter . If you like what I do, sponsor me . πŸ™

Series Outline

  • Numbers in Verilog - introduction to numbers in Verilog
  • Vectors and Arrays (this post) - working with Verilog vectors and arrays
  • Multiplication with DSPs - efficient multiplication with FPGA DSPs
  • Fixed-Point Numbers in Verilog - precision without complexity
  • Division in Verilog - divided we stand
  • More maths to follow

What is a Vector?

A quick recap from Numbers in Verilog :

By default, a Verilog register or wire is 1 bit wide. This is a scalar :

A scalar can only hold 0 or 1 1 .

We need a vector to hold something larger.

A vector is declared like this: type [upper:lower] name;

a , b , and c are vectors:

  • Wire a handles 0-63 inclusive (2 6 is 64).
  • Register b handles 0-255 inclusive (2 8 is 256).
  • Logic c handles 0-4095 inclusive (2 12 is 4096).

With that recap out of the way, let’s look at some things we can do with vectors.

Slicing Vectors

You select an individual bit using its index; for example:

You select a subset by specifying the start and end bits:

You can also use the concat operator {} to select bits from vectors. The following example is equivalent to the one above:

Rather than specify an end bit, you can specify a width with - and + .

These three assignments all select the same four bits:

ProTip: The start bit can be a variable, but not the width.

Loss of Sign

With signed variables, using slices will make the value unsigned, even if you select the whole range!

However, you can force a variable to be signed with the $signed system function:

Produces the following:

$signed is no panacea: sign extension can still catch you out.

Configurable Widths

Avoid hard-coding vector widths; it limits your design flexibility.

Parameters provide a simple way to configure vector widths:

The width of a vector often depends on another parameter, so calculating it yourself isn’t ideal.

Imagine you’re creating a game engine where the number of sprites is configurable:

Changing the sprite count will break the design if we hardcode the width.

Verilog 2005 introduced $clog2 to handle this.

Calculating Widths

The $clog2 function returns the ceiling of the logarithm to base 2.

For example, $clog2(10) = 4 because 2 3 < 10 ≀ 2 4 .

If you need to handle N things (such as sprites or memory locations), then $clog2(N) will tell you how wide your vector needs to be:

$clog2 is handy, but you need to be careful.

If you’re specifying a maximum value (rather than a count), it doesn’t do what you want:

$clog2 returns ‘8’, giving a voltage range of 0-255 inclusive. 256 is out of range.

If you’re specifying a maximum value, you need to add one to the value passed to $clog2 :

This problem is often hidden because it doesn’t occur if your parameter isn’t a power of 2. For example, if you specify ‘240’ as your MAX_VOLTAGE , you won’t see any issues. Later, you increase MAX_VOLTAGE to ‘256’, and the design has a subtle bug.

A Bit Significant

Earlier, we said a vector was declared like this: type [upper:lower] name;

A more general definition is: type [msb_index:lsb_index] name;

Where msb_index is the most significant bit index, and lsb_index is the least significant bit index.

The usual way of declaring vectors has the least significant bit at the lowest index (LSB first):

The most significant bit of a is stored in a[5] and that of b in b[11] .

Alternatively, we can declare vectors with the most significant bit at the lowest index (MSB first):

The most significant bit of c is stored in c[0] and that of d in d[0] .

Switching Ends

MSB-first vectors are comparatively rare in Verilog. However, some hardware interfaces send the most significant bit first, for example, I 2 C.

Say you’ve got an MSB first byte from I 2 C and want to convert it to LSB first.

You could try directly swapping the order:

Alas, some tools won’t let you mix LSB- and MSB-first vectors in one expression.

A more general approach is to reverse the bits explicitly. All bits are swapped in parallel:

Updating individual bits is tedious, but a for loop can handle this for us:

Verilog for is NOT like a software loop: this for loop is unrolled into parallel bit swaps.

Big Endian, Little Endian

So far, we’ve been talking about ordering at the bit level, but it also occurs in the context of bytes. If you have a 32-bit word, do you store the least significant byte at the lowest address (little-endian) or the most significant byte at the lowest address (big-endian)?

RISC-V, x86, and ARM are little-endian, while Internet protocols (TCP/IP) and Motorola 68K are big-endian. There’s also the cursed middle-endian, but I won’t discuss that here.

I’m still writing this content.

What’s Next?

If you enjoyed this post, please sponsor me . Sponsors help me create more FPGA and RISC-V projects for everyone, and they get early access to blog posts and source code. πŸ™

Part three covers Multiplication with DSPs or jump ahead to Fixed-Point Numbers .

You can also check out our other maths posts: division , square root , and sine & cosine .

We’re ignoring X and Z for the purpose of this introduction. See Numbers in Verilog .  ↩︎

  • The Verilog-AMS Language
  • Analog Processes
  • Assignment Statements

Assignment Statements 

Contribution .

A contribution statement is used to give values to continuous signals, in particular to branch potentials or flows:

This statement says that the voltage on the branch named β€˜res’ should be driven so that the voltage on the branch should equal r multiplied by the current through the branch.

Contributions may be either explicit, as above, or implicit. Implicit contributions have the target on both sides of the contribution operator. For example:

This implements the series combination of a resistor and a capacitor.

Implicit contributions to branch flows can be used to easily create series combinations whereas implicit contributions to branch potentials can be used to create parallel combinations. For example, the following creates the parallel combination of an inductor and a conductor:

Multiple contributions to the same branch in the same analog process accumulate. For example:

This is equivalent to:

Multiple contributions to a branch flow can be viewed as creating multiple parallel branches. For example, the above example is equivalent to the parallel combination of the output of a controlled current source, a conductor, and a capacitor. Similarly, multiple contributions to a branch potential can be viewed as creating multiple series branches.

The target (left side) must be a branch signal: an access function applied to a continuous branch. The branch may be a named (or explicit) branch, or it may be an unnamed (or implicit) branch, which are given as a single net or a pair of nets. When an implicit branch is given as a pair of nets, the branch is assumed to connect the two nets. When an implicit branch is specified as a single net, the branch is assumed to connect that net to ground.

Here is a resistor module that uses a explicitly declared or named branch:

Here is a resistor module that uses a implicitly declared or unnamed branch:

Descriptions that employ unnamed branches are a little more compact, but also the formulation of the branches is constrained (multiple contributions to flows give a shunt toplogy and to potentials gives a series topology). For this reason people use unnamed branches with the branch topology is simple, and switch to named branches for the more complicated topologies.

The actual contributions occur after the analog block has been evaluated, meaning that the branch values do not change between statements in the analog block. As such, so as long as the values of the right-hand side expressions are not affected, the order of the contribution statements is inconsequential. So for example, these two analog blocks are equivalent:

Indirect Assignment 

An indirect assignment is an alternative to the contribution statement. It also drives a particular branch potential or flow so that a given equation is satisfied, but in this case the driven branch potential or flow need not be in the specified equation. This feature is rarely needed, however it occasionally allows you to describe a component that would cumbersome to describe with contributions. For example, it is possible to describe an ideal opamp using:

This can be read as β€˜drive V(out) such that V(pin,nin) == 0’.

The left side of the equation must be either a branch potential or flow, the right side is an expression. The equation may be implicit or explicit.

The driven branch must not also be a target of a contribution statement.

Assignment 

A assignment evaluates the expression on its right hand side and then immediately assigns the value to the variable on its left hand side:

The target (left side) of an analog assignment statement may only be a integer or real variable. It may not be signal or a wire.

Contribution versus Assignment 

For people new to Verilog-A and Verilog-AMS, contribution and assignment seem to be doing very similar things, and this can confuse them. Here the differences between contribution and assignment are highlighted.

Using Continuous Assignment to Model Combinational Logic in Verilog

In this post, we talk about continuous assignment in verilog using the assign keyword. We then look at how we can model basic logic gates and multiplexors in verilog using continuous assignment.

There are two main classes of digital circuit which we can model in verilog – combinational and sequential .

Combinational logic is the simplest of the two, consisting solely of basic logic gates, such as ANDs, ORs and NOTs. When the circuit input changes, the output changes almost immediately (there is a small delay as signals propagate through the circuit).

In contrast, sequential circuits use a clock and require storage elements such as flip flops . As a result, output changes are synchronized to the circuit clock and are not immediate.

In this post, we talk about the techniques we can use to design combinational logic circuits in verilog. In the next post, we will discuss the techniques we use to model basic sequential circuits .

Continuous Assignment in Verilog

We use continuous assignment to drive data onto verilog net types in our designs. As a result of this, we often use continuous assignment to model combinational logic circuits.

We can actually use two different methods to implement continuous assignment in verilog.

The first of these is known as explicit continuous assignment. This is the most commonly used method for continuous assignment in verilog.

In addition, we can also use implicit continuous assignment, or net declaration assignment as it is also known. This method is less common but it can allow us to write less code.

Let's look at both of these techniques in more detail.

  • Explicit Continuous Assignment

We normally use the assign keyword when we want to use continuous assignment in verilog. This approach is known as explicit continuous assignment.

The verilog code below shows the general syntax for continuous assignment using the assign keyword.

The <variable> field in the code above is the name of the signal which we are assigning data to. We can only use continuous assignment to assign data to net type variables.

The <value> field can be a fixed value or we can create an expression using the verilog operators we discussed in a previous post. We can use either variable or net types in this expression.

When we use continuous assignment, the <variable> value changes whenever one of the signals in the <value> field changes state.

The code snippet below shows the most basic example of continuous assignment in verilog. In this case, whenever the b signal changes states, the value of a is updated so that it is equal to b.

  • Net Declaration Assignment

We can also use implicit continuous assignment in our verilog designs. This approach is also commonly known as net declaration assignment in verilog.

When we use net declaration assignment, we place a continuous assignment in the statement which declares our signal. This can allow us to reduce the amount of code we have to write.

To use net declaration assignment in verilog, we use the = symbol to assign a value to a signal when we declare it.

The code snippet below shows the general syntax we use for net declaration assignment.

The variable and value fields have the same function for both explicit continuous assignment and net declaration assignment.

As an example, the verilog code below shows how we would use net declaration assignment to assign the value of b to signal a.

Modelling Combinational Logic Circuits in Verilog

We use continuous assignment and the verilog operators to model basic combinational logic circuits in verilog.

To show we would do this, let's look at the very basic example of a three input and gate as shown below.

To model this circuit in verilog, we use the assign keyword to drive the data on to the and_out output. This means that the and_out signal must be declared as a net type variable, such as a wire.

We can then use the bit wise and operator (&) to model the behavior of the and gate.

The code snippet below shows how we would model this three input and gate in verilog.

This example shows how simple it is to design basic combinational logic circuits in verilog. If we need to change the functionality of the logic gate, we can simply use a different verilog bit wise operator .

If we need to build a more complex combinational logic circuit, it is also possible for us to use a mixture of different bit wise operators.

To demonstrate this, let's consider the basic circuit shown below as an example.

To model this circuit in verilog, we need to use a mixture of the bit wise and (&) and or (|) operators. The code snippet below shows how we would implement this circuit in verilog.

Again, this code is relatively straight forward to understand as it makes use of the verilog bit wise operators which we discussed in the last post.

However, we need to make sure that we use brackets to model more complex logic circuit. Not only does this ensure that the circuit operates properly, it also makes our code easier to read and maintain.

Modelling Multiplexors in Verilog

Multiplexors are another component which are commonly used in combinational logic circuits.

In verilog, there are a number of ways we can model these components.

One of these methods uses a construct known as an always block . We normally use this construct to model sequential logic circuits, which is the topic of the next post in this series. Therefore, we will look at this approach in more detail the next blog post.

In the rest of this post, we will look at the other methods we can use to model multiplexors.

  • Verilog Conditional Operator

As we talked about in a previous blog, there is a conditional operator in verilog . This functions in the same way as the conditional operator in the C programming language.

To use the conditional operator, we write a logical expression before the ? operator which is then evaluated to see if it is true or false.

The output is assigned to one of two values depending on whether the expression is true or false.

The verilog code below shows the general syntax which the conditional operator uses.

From this example, it is clear how we can create a basic two to one multiplexor using this operator.

However, let's look at the example of a simple 2 to 1 multiplexor as shown in the circuit diagram below.

The code snippet below shows how we would use the conditional operator to model this multiplexor in verilog.

  • Nested Conditional Operators

Although this is not common, we can also write code to build larger multiplexors by nesting conditional operators.

To show how this is done, let's consider a basic 4 to 1 multiplexor as shown in the circuit below.

To model this in verilog using the conditional operator, we treat the multiplexor circuit as if it were a pair of two input multiplexors.

This means one multiplexor will select between inputs A and B whilst the other selects between C and D. Both of these multiplexors use the LSB of the address signal as the address pin.

To create the full four input multiplexor, we would then need another multiplexor.

This takes the outputs from the first two multiplexors and uses the MSB of the address signal to select between them.

The code snippet below shows the simplest way to do this. This code uses the signals mux1 and mux2 which we defined in the last example.

However, we could easily remove the mux1 and mux2 signals from this code and instead use nested conditional operators.

This reduces the amount of code that we would have to write without affecting the functionality.

The code snippet below shows how we would do this.

As we can see from this example, when we use conditional operators to model multiplexors in verilog, the code can quickly become difficult to understand. Therefore, we should only use this method to model small multiplexors.

  • Arrays as Multiplexors

It is also possible for us to use verilog arrays to build simple multiplexors.

To do this we combine all of the multiplexor inputs into a single array type and use the address to point at an element in the array.

To get a better idea of how this works in practise, let's consider a basic four to one multiplexor as an example.

The first thing we must do is combine our input signals into an array. There are two ways in which we can do this.

Firstly, we can declare an array and then assign all of the individual bits, as shown in the verilog code below.

Alternatively we can use the verilog concatenation operator , which allows us to assign the entire array in one line of code.

To do this, we use a pair of curly braces - { } - and list the elements we wish to include in the array inside of them.

When we use the concatenation operator we can also declare and assign the variable in one statement, as long as we use a net type.

The verilog code below shows how we can use the concatenation operator to populate an array.

As verilog is a loosely typed language , we can use the two bit addr signal as if it were an integer type. This signal then acts as a pointer that determines which of the four elements to select.

The code snippet below demonstrates this method in practise. As the mux output is a wire, we must use continuous assignment in this instance.

What is the difference between implicit and explicit continuous assignment?

When we use implicit continuous assignment we assign the variable a value when we declare. When we use explicit continuous assignment we use the assign keyword to assign a value.

Write the code for a 2 to 1 multiplexor using any of the methods discussed we discussed.

Write the code for circuit below using both implicit and explicit continuous assignment.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Table of Contents

Sign up free for exclusive content.

Don't Miss Out

We are about to launch exclusive video content. Sign up to hear about it first.

Verilog Concatenation

Multi-bit Verilog wires and variables can be clubbed together to form a bigger multi-net wire or variable using concatenation operators { and } separated by commas. Concatenation is also allowed to have expressions and sized constants as operands in addition to wires and variables.

Size of each operand must be known in order to calculate the complete size of concatenation.

Verilog Concatenation Example

Here is a working design example of concatenation of inputs to form different outputs. Concatenated expressions can be simply displayed or assigned to any wire or variable, not necessarily outputs.

Note that out2[2:1] is always a constant 2'b01.

Replication Operator

When the same expression has to be repeated for a number of times, a replication constant is used which needs to be a non-negative number and cannot be X, Z or any variable. This constant number is also enclosed within braces along with the original concatenation operator and indicates the total number of times the expression will be repeated.

Replication expressions cannot appear on the left hand side of any assignment and cannot be connected to output or inout ports.

Note that a got repeated twice and b got repeated thrice.

Operands will be evaluated only once when the replication expression is executed even if the constant is zero.

The Verilog replication operator {} is commonly used in digital design to create bit patterns for initializing registers, memory arrays, or lookup tables. Here is an example:

Suppose we want to initialize a 16-bit register counter to count from 0 to 15 in a clock cycle. We can use the replication operator to create a bit pattern that represents the binary values 0 to 15, and assign it to the counter register:

Nested Replication

A replication expression is allowed to be used inside regular concatenation expressions. Taking the above example as base, a and b has been included into the total concatenated expression.

In the above example, we use the replication operator {16{1'b0}} to create a 16-bit bit pattern consisting of 16 zeros (1'b0). This initializes the counter register to 0 at the start of the simulation.

Illegal usage

This results in a compilation error as shown below.

Verilog Sign Extension

In Verilog, sign extension is a way of extending a signed number with fewer bits to a wider signed number by replicating the sign bit. Basically, it is used when performing arithmetic or logical operations on numbers with different bit widths.

For example, let's say we have a 4-bit two's complement number, -3, represented as 1101. If we want to add this number to another 8-bit two's complement number, say -10, represented as 11110110, we first need to sign extend the 4-bit number to 8 bits to make it compatible with the 8-bit number. To sign extend the 4-bit number, we replicate its most significant bit (the sign bit) to fill the additional bits, resulting in 11111101. We can then add this sign-extended 4-bit number to the 8-bit number using normal Verilog arithmetic operations.

Here's an example of how to sign extend a 4-bit signed number to an 8-bit signed number in Verilog using concatenation discussed above:

In this example, the input is a 4-bit signed number called input_num , and the output is an 8-bit signed number called output_num . The sign bit of the input number is checked, and if it's 1, the output number is extended with ones, otherwise it's extended with zeros.

Note that the syntax for sign extension may vary depending on the specific implementation and tools being used.

DMCA.com Protection Status

IMAGES

  1. Verilog Scalar and Vector

    verilog vector assignment

  2. Verilog HDL Complete Series

    verilog vector assignment

  3. Verilog HDL: Design Circuits Using Vectors

    verilog vector assignment

  4. GitHub

    verilog vector assignment

  5. PPT

    verilog vector assignment

  6. vector 0

    verilog vector assignment

VIDEO

  1. Digital Design With Verilog @NPTEL 2024 Assignment 11 Solutions

  2. DIGITAL DESIGN WITH VERILOG ASSIGNMENT 1 2024 KEY

  3. Digital Design With Verilog @NPTEL 2024 Assignment 10 Solutions

  4. System Design Through Verilog NPTEL week 3 Assignment 3

  5. Fundamentals Pen Tool Vector Assignment

  6. System Design Through Verilog

COMMENTS

  1. Verilog Assignments

    This is used to assign values onto scalar and vector nets and happens whenever there is a change in the RHS. It provides a way to model combinational logic without specifying an interconnection of gates and makes it easier to drive the net with logical expressions. // Example model of an AND gate. wire a, b, c;

  2. Vector assignment in Verilog

    It is my first attempt to use verilog. I have defined an 8-bit bidirectional port, a data register and a data direction register in the following way: inout [7:0] pa; // 8-bit bidirectional par...

  3. Verilog scalar and vector

    Verilog scalar and vector. Scalar and Vector. Bit-selects. Part-selects. Common Errors. Verilog needs to represent individual bits as well as groups of bits. For example, a single bit sequential element is a flip-flop. However a 16-bit sequential element is a register that can hold 16 bits. For this purpose, Verilog has scalar and vector nets ...

  4. Verilog Vectors and Arrays

    What is a Vector? A quick recap from Numbers in Verilog: By default, a Verilog register or wire is 1 bit wide. This is a scalar: wire x; // 1 bit wire reg y; // also 1 bit logic z; // me too! A scalar can only hold 0 or 1 1. ... These three assignments all select the same four bits:

  5. Assigning a zero to a vector in Verilog

    1 Answer. Sorted by: SystemVerilog has the bit fill literals '0, '1, 'x, and 'z. This means fill a vector with a digit to whatever width is required by the context. (In a self-determined context, it is just a single bit) You should write: assign x = '0; Share. Cite.

  6. Verilog Arrays and Memories

    An array can be formed for any of the different data-types supported in Verilog. Note that a memory of n 1-bit reg is not the same as an n-bit vector reg. Array Assignment. y1 = 0; // Illegal - All elements can't be assigned in a single go. y2[0] = 8'ha2; // Assign 0xa2 to index=0.

  7. Verilog assign statement

    Verilog assign statement. Signals of type wire or a similar wire like data type requires the continuous assignment of a value. For example, consider an electrical wire used to connect pieces on a breadboard. As long as the +5V battery is applied to one end of the wire, the component connected to the other end of the wire will get the required ...

  8. PDF Intro to Verilog

    Microsoft PowerPoint - L03_Verilog v2.pptx. Intro to Verilog. β€’ Wires - theory vs reality (Lab1) β€’ Hardware Description Languages. β€’ Verilog -- structural: modules, instances -- dataflow: continuous assignment -- sequential behavior: always blocks -- pitfalls -- other useful features. Reminder: Lab #1 due by 9pm tonight.

  9. Assignment Statements

    Assignment. A assignment evaluates the expression on its right hand side and then immediately assigns the value to the variable on its left hand side: a = b + c; The target (left side) of an analog assignment statement may only be a integer or real variable. It may not be signal or a wire.

  10. Assigning to a parameterized 2d Verilog array

    1. To assign unpacked 2d array in SystemVerilog with a single line: Verilog cannot be done in a single line. It must use a for-loop: some_array[i] <= {element_width{1'b1}}; Suppose: num_elements = 4 element_width = 8 Making it more complicated I want each element to get "0xFA" So now - my ONLY option is to use the for-loop approach ? There's no ...

  11. Using Continuous Assignment to Model Combinational Logic in Verilog

    To use net declaration assignment in verilog, we use the = symbol to assign a value to a signal when we declare it. ... // Using vector assignment assign in_vec = {d, c, b, a}; // Declare and assign the vector in one line wire [3:0] in_vec = {d, c, b, a}; As verilog is a loosely typed language, we can use the two bit addr signal as if it were ...

  12. How is the assignment sequence done in Verilog?

    The answer to this question is strongly related to Verilog concepts I described in my answer to another question about Verilog non-blocking assignment (NBA).. The straightway answer to your question is very simple: all assignments are performed at the same simulation time slot, i.e. both blocking and non-blocking assignments will be evaluated and assigned before the following time slot (which ...

  13. Combinational Logic with assign

    The verilog assign statement is typically used to continuously drive a signal of wire datatype and gets synthesized as combinational logic. Here are some more design examples using the assign statement.. Example #1 : Simple combinational logic. The code shown below implements a simple digital combinational logic which has an output wire z that is driven continuously with an assign statement to ...

  14. Verilog Concatenation

    Verilog Sign Extension. Multi-bit Verilog wires and variables can be clubbed together to form a bigger multi-net wire or variable using concatenation operators { and } separated by commas. Concatenation is also allowed to have expressions and sized constants as operands in addition to wires and variables. Size of each operand must be known in ...

  15. verilog

    1. I have a module that can be configured with two parameters. Depending on the values of these parameters, I either need to pad or truncate an output vector when assigning it to an input vector. For example: module my_mod(vector_in, vector_out); parameter IN_BITS = 10; parameter OUT_BITS = 8;

  16. system verilog

    First IEEE appearance is IEEE 1364-2001 (Verilog) Β§ 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM: The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then ...

  17. What is supposed to happen in Verilog if a signal of one width is

    Verilog's rules are: if you copy a narrower value into a wider target, it is zero-extended (zero MSBs added to the left), or sign-extended into the target. Whether it is zero or sign-extended is determined by the signedness of the right-hand-side expression.