courses:system_design:vhdl_language_and_syntax:sequential_statements:variables

Fundamentals

  • Name within process declarations
  • Known only in this process
  • Immediate assignment
  • Keep the last value
  • Signal to variable
  • Variable to signal
  • Types have to match

Variables can only be defined in a process and they are only accessible within this process.

Variables and signals show a fundamentally different behavior. In a process, the last signal assignment to a signal is carried out when the process execution is suspended. Value assignments to variables, however, are carried out immediately. To distinguish between a signal and a variable assignment different symbols are used: ’⇐’ indicates a signal assignment and ’:=’ indicates a variable assignment.

Variables vs. Signals

A,B,C: integer; signal Y, Z : integer;   begin process (A,B,C) variable M, N: integer; begin M := A; N := B; Z <= M + N; M := C; Y <= M + N; end process; A,B,C: integer; signal Y, Z : integer; signal M, N : integer; begin process (A,B,C,M,N)     begin M <= A; N <= B; Z <= M + N; M <= C; Y <= M + N; end process;
  • Signal values are assigned after the process execution
  • Only the last signal assignment is carried out
  • M ⇐ A; is overwritten by M ⇐ C;
  • The 2nd adder input is connected to C

The two processes shown in the example implement different behavior as both outputs Z and Y will be set to the result of B+C when signals are used instead of variables.

Please note that the intermediate signals have to added to the sensitivity list, as they are read during process execution.

Use of Variables

  • signal to variable assignment
  • execution of algorithm
  • variable to signal assignments
  • no access to variable values outside their process
  • variables store their value until the next process call

Variables are especially suited for the implementation of algorithms. Usually, the signal values are copied into variables before the algorithm is carried out.

The result is assigned to a signal again afterwards.

Variables keep their value from one process call to the next, i.e. if a variable is read before a value has been assigned, the variable will have to show storage behavior. That means it will have to be synthesized to a latch or flip flop respectively.

Variables: Example

  • Parity calculation
  • Synthesis result:

In the example a further difference between signals and variables is shown. While a (scalar) signal can always be associated with a line, this is not valid for variables. In the example the for loop is executed four times. Each time the variable TMP describes a different line of the resulting hardware. The different lines are the outputs of the corresponding XOR gates.

Shared Variables (VHDL’93)

  • Accessible by all processes of an architecture (shared variables)
  • Can introduce non determinism

In VHDL 93, global variables are allowed.

These variables are not only visible within a process but within the entire architecture.

The problem may occur, that two processes assign a different value to a global variable at the same time. It is not clear then, which of these processes assigns the value to the variable last.

This can lead to a non deterministic behavior!

In synthesizable VHDL code global variables must not be used.

Chapters of System Design > VHDL Language and Syntax > Sequential Statements

  • Sequential Statements
  • IF Statement
  • CASE Statement
  • WAIT Statement

Chapters of System Design > VHDL Language and Syntax

  • General Issues
  • VHDL Structural Elements
  • Process Execution
  • Extended Data Types
  • Subprograms
  • Subprogram Declaration and Overloading
  • Concurrent Statements

what is variable assignment in vhdl

GitHub

Assignment Symbol in VHDL

VHDL assignments are used to assign values from one object to another. In VHDL there are two assignment symbols:

Either of these assignment statements can be said out loud as the word “gets”. So for example in the assignment: test <= input_1; You could say out loud, “The signal test gets (assigned the value from) input_1.”

Note that there is an additional symbol used for component instantiations (=>) this is separate from an assignment.

Also note that <= is also a relational operator (less than or equal to). This is syntax dependent. If <= is used in any conditional statement (if, when, until) then it is a relational operator , otherwise it’s an assignment.

One other note about signal initialization: Signal initialization is allowed in most FPGA fabrics using the := VHDL assignment operator. It is good practice to assign all signals in an FPGA to a known-value when the FPGA is initialized. You should avoid using a reset signal to initialize your FPGA , instead use the := signal assignment.

Learn Verilog

Leave A Comment Cancel reply

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

  • Network Sites:
  • Technical Articles
  • Market Insights

All About Circuits

  • Or sign in with
  • iHeartRadio

All About Circuits

The Variable: A Valuable Object in Sequential VHDL

Join our engineering community sign-in with:.

This article will discuss the important features of variables in VHDL.

The previous article in this series discussed that sequential statements allow us to describe a digital system in a more intuitive way. Variables are useful objects that can further facilitate the behavioral description of a circuit. This article will discuss the important features of variables. Several examples will be discussed to clarify the differences between variables and signals. Let’s first review VHDL signals.

Multiple Assignments to a Signal

VHDL uses signals to represent the circuit interconnects or wires. For example, consider the circuit in Figure 1.

what is variable assignment in vhdl

The architecture of the VHDL code for this circuit is

As you can see, a signal has a clear mapping into hardware: it becomes a (group of) wire(s). Does it make sense to have multiple assignments to a signal? For example, consider the following code section:

If these two assignments are in the concurrent part of the code, then they are executed simultaneously. We can consider the equivalent hardware of the above code as shown in Figure 2.

what is variable assignment in vhdl

Figure 2 suggests that multiple assignments to a signal in the concurrent part of the code is not a good idea because there can be a conflict between these assignments. For example, if A=C=0 and B=D=1, the first line would assign sig1 = (0 and 1) =0, while the second would attempt to assign sig1 = (0 or 1) = 1. That’s why, in the concurrent part of the code, VHDL doesn’t allow multiple assignments to a signal. What if these two assignments were in the sequential part of the code? A compiler may accept multiple assignments inside a process but, even in this case, only the last assignment will survive and the previous ones will be ignored. To explain this, note that a process can be thought of as a black box whose inner operation may be given by some abstract behaviour description. This description uses sequential statements. The connection between the process black box and the outside world is achieved through the signals. The process may read the value of these signals or assign a value to them. So VHDL uses signals to connect the sequential part of the code to the concurrent domain. Since a signal is connected to the concurrent domain of the code, it doesn’t make sense to assign multiple values to the same signal. That’s why, when facing multiple assignments to a signal, VHDL considers only the last assignment as the valid assignment.

Updating the Value of a Signal

The black box interpretation of a process reveals another important property of a signal assignment inside a process: When we assign a value to a signal inside a process, the new value of the signal won’t be available immediately. The value of the signal will be updated only after the conclusion of the current process run. The following example further clarifies this point. This example uses the VHDL “if” statements. Please note that we’ll see more examples of this statement in future articles; however, since it is similar to the conditional structures of other programming languages, the following code should be readily understood. You can find a brief description of this statement in a previous article.

Example: Write the VHDL code for a counter which counts from 0 to 5.

One possible VHDL description is given below:

In this example, sig1 is defined as a signal of type integer in the declarative part of the architecture. With each rising edge of clk, the value of the signal sig1 will increase by one. When sig1 reaches 6, the condition of the “if” statement in line 14 will be evaluated as true and sig1 will take the value zero. So it seems that sig1 , whose value is eventually passed to the output port out1 , will always take the values in the range 0 to 5. In other words, it seems that the “if” statement of line 14 will never let sig1 take the value 6. Let’s examine the operation of the code more closely.

Assume that a previous run of the process sets sig1 to 5. With the next rising edge of clk , the statements inside the “if” statement of line 12 will be executed. Line 13 will add one to the current value of sig1, which is 5, and assign the result to sig1 . Hence, the new value of sig1 will be 6; however, we should note that the value of the signal sig1 will be updated only after the conclusion of the current process run. As a result, in this run of the process, the condition of the “if” statement in line 14 will be evaluated as false and the corresponding “then” branch will be bypassed. Reaching the end of the process body, the value of sig1 will be updated to 6. While we intended sig1 to be in the range 0 to 5, it can take the value 6!

Similarly, at the next rising edge of clk, line 13 will assign 7 to sig1 . However, the signal value update will be postponed until we reach the end of the process body. In this run of the process, the condition of the “if” statement in line 14 returns true and, hence, line 15 will set sig1 to zero. As you see, in this run of the process, there are two assignments to the same signal. Based on the discussion of the previous section, only the last assignment will take effect, i.e. the new value of sig1 will be zero. Reaching the end of this process run, sig1 will take this new value. As you see, sig1 will take the values in the range from 0 to 6 rather than from 0 to 5! You can verify this in the following ISE simulation of the code.

what is variable assignment in vhdl

Hence, when using signals inside a process, we should note that the new value of a signal will be available at the end of the current run of the process. Not paying attention to this property is a common source of mistake particularly for those who are new to VHDL.

To summarize our discussion so far, a signal models the circuit interconnections. If we assign multiple values to a signal inside a process, only the last assignment will be considered. Moreover, the assigned value will be available at the end of the process run and the updates are not immediate.

Variable: Another Useful VHDL Object

As discussed in a previous article, sequential statements allow us to have an algorithmic description of a circuit. The code of such descriptions is somehow similar to the code written by a computer programming language. In computer programming, “variables” are used to store information to be referenced and used by programs. With variables, we can more easily describe an algorithm when writing a computer program. That’s why, in addition to signals, VHDL allows us to use variables inside a process. While both signals and variables can be used to represent a value, they have several differences. A variable is not necessarily mapped into a single interconnection. Besides, we can assign several values to a variable and the new value update is immediate. In the rest of the article, we will explain these properties in more detail.

Before proceeding, note that variables can be declared only in a sequential unit such as a process (the only exception is a “shared” variable which is not discussed in this article). To get more comfortable with VHDL variables, consider the following code segment which defines variable var1 .

Similar to a signal, a variable can be of any data type (see the previous articles in this series to learn more about different data types). However, variables are local to a process. They are used to store the intermediate values and cannot be accessed outside of the process. Moreover, as shown by line 4 of the above code, the assignment to a variable uses the “:=” notation, whereas, the signal assignment uses “<=”.

Multiple Assignments to a Variable

Consider the following code. In this case, a variable, var1 , of type std_logic is defined. Then in lines 12, 13, and 14, three values are assigned to this variable.

Figure 4 shows the RTL schematic of the above code which is generated by Xilinx ISE.

what is variable assignment in vhdl

It’s easy to verify that the produced schematic matches the behavior described in the process; however, this example shows that mapping variables into the hardware is somehow more complicated than that of signals. This is due to the fact that the sequential statements describe the behavior of a circuit.  As you can see, in this example, each variable assignment operation of lines 13 and 14 have created a different wire though both of these two assignments use the same variable name, i.e. var1 .

Updating the Value of a Variable

Variables are updated immediately. To examine this, we’ll modify the code of the above counter and use a variable instead of a signal. The code is given below:

Since the new value of a variable is immediately available, the output will be in the range 0 to 5. This is shown in the following ISE simulation result.

what is variable assignment in vhdl

  • A signal models the circuit interconnections. If we assign multiple values to a signal inside a process, only the last assignment will be considered. Moreover, the assigned value will be available at the end of the current process run and the updates are not immediate.
  • A single variable can produce several circuit interconnections.
  • We can assign multiple values to the same variable and the assigned new values will take effect immediately.
  • Similar to a signal, a variable can be of any data type.
  • Variables are local to a process. They are used to store the intermediate values and cannot be accessed outside of the process.
  • The assignment to a variable uses the “:=” notation, whereas, the signal assignment uses “<=”.

To see a complete list of my articles, please visit this page .

Related Content

  • Reducing Distortion in Tape Recordings with Hysteresis in SPICE
  • Explainer Video: Moving Object Simulation
  • Test & Measurement in Quantum Computing
  • Sequential VHDL: If and Case Statements
  • Introduction to Sequential VHDL Statements
  • What is Design Rule Checking in PCB Design?

Learn More About:

  • programmable logic
  • sequential vhdl
  • vhdl variable

what is variable assignment in vhdl

You May Also Like

what is variable assignment in vhdl

NEMA vs. IP: Differences Explained

In Partnership with MacroFab

what is variable assignment in vhdl

Understanding the Non-Idealities of Magnetically Coupled RF Transformers

by Dr. Steve Arar

what is variable assignment in vhdl

Nordic, MediaTek, and U-blox Take on New Wireless Frontiers

by Jake Hertz

what is variable assignment in vhdl

The Internet’s “Father Time” David L. Mills Dies at 85

by Duane Benson

what is variable assignment in vhdl

MCU Roundup: 3 New MCUs Push Performance at the Edge

by Aaron Carman

All About Circuits

Welcome Back

Don't have an AAC account? Create one now .

Forgot your password? Click here .

All About Circuits Logo

Chapter 4 - Behavioral Descriptions

Section 2 - using variables.

Declaration ---- used in ----> Process
Procedure
Function
Syntax
Rules and Examples
A Variable may be given an explicit initial value when it is declared. If a variable is not given an explicit value, it's default value will be the leftmost value ( ) of its declared type.
Variables within subprograms (functions and procedures) are initialised each time the subprogram is called:
Variables in processes, except for "FOR LOOP" variables, receive their initial values at the start of the simulation time (time = 0 ns)
Synthesis Issues
Variables are supported for synthesis, providing they are of a type acceptable to the logic synthesis tool.

In a "clocked process", each variable which has its value read before it has had an assignment to it will be synthesised as the output of a register.

In a "combinational process", reading a variable before it has had an assignment may cause a latch to be synthesised.

Variables declared in a subprogram are synthesised as combinational logic.

Whats New in '93

In VHDL -93, shared variables may be declared within an architecture, block, generate statement, or package:

  • Getting started with vhdl
  • D-Flip-Flops (DFF) and latches
  • Digital hardware design using VHDL in a nutshell
  • Identifiers
  • Protected types
  • Recursivity
  • Resolution functions, unresolved and resolved types
  • Static Timing Analysis - what does it mean when a design fails timing?

vhdl Getting started with vhdl Signals vs. variables, a brief overview of the simulation semantics of VHDL

Fastest entity framework extensions.

This example deals with one of the most fundamental aspects of the VHDL language: the simulation semantics. It is intended for VHDL beginners and presents a simplified view where many details have been omitted (postponed processes, VHDL Procedural Interface, shared variables...) Readers interested in the real complete semantics shall refer to the Language Reference Manual (LRM).

Signals and variables

Most classical imperative programming languages use variables. They are value containers. An assignment operator is used to store a value in a variable:

and the value currently stored in a variable can be read and used in other statements:

VHDL also uses variables and they have exactly the same role as in most imperative languages. But VHDL also offers another kind of value container: the signal. Signals also store values, can also be assigned and read. The type of values that can be stored in signals is (almost) the same as in variables.

So, why having two kinds of value containers? The answer to this question is essential and at the heart of the language. Understanding the difference between variables and signals is the very first thing to do before trying to program anything in VHDL.

Let us illustrate this difference on a concrete example: the swapping.

Note: all the following code snippets are parts of processes. We will see later what processes are.

swaps variables a and b . After executing these 3 instructions, the new content of a is the old content of b and conversely. Like in most programming languages, a third temporary variable ( tmp ) is needed. If, instead of variables, we wanted to swap signals, we would write:

with the same result and without the need of a third temporary signal!

Note: the VHDL signal assignment operator <= is different from the variable assignment operator := .

Let us look at a second example in which we assume that the print subprogram prints the decimal representation of its parameter. If a is an integer variable and its current value is 15, executing:

will print:

If we execute this step by step in a debugger we can see the value of a changing from the initial 15 to 30, 25 and finally 5.

But if s is an integer signal and its current value is 15, executing:

If we execute this step by step in a debugger we will not see any value change of s until after the wait instruction. Moreover, the final value of s will not be 15, 30, 25 or 5 but 3!

This apparently strange behavior is due the fundamentally parallel nature of digital hardware, as we will see in the following sections.

Parallelism

VHDL being a Hardware Description Language (HDL), it is parallel by nature. A VHDL program is a collection of sequential programs that run in parallel. These sequential programs are called processes:

The processes, just like the hardware they are modelling, never end: they are infinite loops. After executing the last instruction, the execution continues with the first.

As with any programming language that supports one form or another of parallelism, a scheduler is responsible for deciding which process to execute (and when) during a VHDL simulation. Moreover, the language offers specific constructs for inter-process communication and synchronization.

The scheduler maintains a list of all processes and, for each of them, records its current state which can be running , run-able or suspended . There is at most one process in running state: the one that is currently executed. As long as the currently running process does not execute a wait instruction, it continues running and prevents any other process from being executed. The VHDL scheduler is not preemptive: it is each process responsibility to suspend itself and let other processes run. This is one of the problems that VHDL beginners frequently encounter: the free running process.

Note: variable a is declared locally while signals s and r are declared elsewhere, at a higher level. VHDL variables are local to the process that declares them and cannot be seen by other processes. Another process could also declare a variable named a , it would not be the same variable as the one of process P3 .

As soon as the scheduler will resume the P3 process, the simulation will get stuck, the simulation current time will not progress anymore and the only way to stop this will be to kill or interrupt the simulation. The reason is that P3 has not wait statement and will thus stay in running state forever, looping over its 3 instructions. No other process will ever be given a chance to run, even if it is run-able .

Even processes containing a wait statement can cause the same problem:

Note: the VHDL equality operator is = .

If process P4 is resumed while the value of signal s is 3, it will run forever because the a = 16 condition will never be true.

Let us assume that our VHDL program does not contain such pathological processes. When the running process executes a wait instruction, it is immediately suspended and the scheduler puts it in the suspended state. The wait instruction also carries the condition for the process to become run-able again. Example:

means suspend me until the value of signal s changes . This condition is recorded by the scheduler. The scheduler then selects another process among the run-able , puts it in running state and executes it. And the same repeats until all run-able processes have been executed and suspended.

Important note: when several processes are run-able , the VHDL standard does not specify how the scheduler shall select which one to run. A consequence is that, depending on the simulator, the simulator's version, the operating system, or anything else, two simulations of the same VHDL model could, at one point, make different choices and select a different process to execute. If this choice had an impact on the simulation results, we could say that VHDL is non-deterministic. As non-determinism is usually undesirable, it would be the responsibility of the programmers to avoid non-deterministic situations. Fortunately, VHDL takes care of this and this is where signals enter the picture.

Signals and inter-process communication

VHDL avoids non determinism using two specific characteristics:

  • Processes can exchange information only through signals
Note: VHDL comments extend from -- to the end of the line.
  • The value of a VHDL signal does not change during the execution of processes

Every time a signal is assigned, the assigned value is recorded by the scheduler but the current value of the signal remains unchanged. This is another major difference with variables that take their new value immediately after being assigned.

Let us look at an execution of process P5 above and assume that a=5 , s=1 and r=0 when it is resumed by the scheduler. After executing instruction a := s + 1; , the value of variable a changes and becomes 2 (1+1). When executing the next instruction r <= a; it is the new value of a (2) that is assigned to r . But r being a signal, the current value of r is still 0. So, when executing a := r + 1; , variable a takes (immediately) value 1 (0+1), not 3 (2+1) as the intuition would say.

When will signal r really take its new value? When the scheduler will have executed all run-able processes and they will all be suspended. This is also referred to as: after one delta cycle . It is only then that the scheduler will look at all the values that have been assigned to signals and actually update the values of the signals. A VHDL simulation is an alternation of execution phases and signal update phases. During execution phases, the value of the signals is frozen. Symbolically, we say that between an execution phase and the following signal update phase a delta of time elapsed. This is not real time. A delta cycle has no physical duration.

Thanks to this delayed signal update mechanism, VHDL is deterministic. Processes can communicate only with signals and signals do not change during the execution of the processes. So, the order of execution of the processes does not matter: their external environment (the signals) does not change during the execution. Let us show this on the previous example with processes P5 and P6 , where the initial state is P5.a=5 , P6.a=10 , s=17 , r=0 and where the scheduler decides to run P5 first and P6 next. The following table shows the value of the two variables, the current and next values of the signals after executing each instruction of each process:

process / instruction
Initial state510170
1810170
181017018
11017018
11017018
1117018
11171018
11171018
After signal update11118

With the same initial conditions, if the scheduler decides to run P6 first and P5 next:

process / instruction
Initial state510170
51170
511710
511710
1811710
181171018
11171018
11171018
After signal update11118

As we can see, after the execution of our two processes, the result is the same whatever the order of execution.

This counter-intuitive signal assignment semantics is the reason of a second type of problems that VHDL beginners frequently encounter: the assignment that apparently does not work because it is delayed by one delta cycle. When running process P5 step-by-step in a debugger, after r has been assigned 18 and a has been assigned r + 1 , one could expect that the value of a is 19 but the debugger obstinately says that r=0 and a=1 ...

Note: the same signal can be assigned several times during the same execution phase. In this case, it is the last assignment that decides the next value of the signal. The other assignments have no effect at all, just like if they never had been executed.

It is time to check our understanding: please go back to our very first swapping example and try to understand why:

actually swaps signals r and s without the need of a third temporary signal and why:

would be strictly equivalent. Try to understand also why, if s is an integer signal and its current value is 15, and we execute:

the two first assignments of signal s have no effect, why s is finally assigned 3 and why the two printed values are 15 and 3.

Physical time

In order to model hardware it is very useful to be able to model the physical time taken by some operation. Here is an example of how this can be done in VHDL. The example models a synchronous counter and it is a full, self-contained, VHDL code that could be compiled and simulated:

In process P1 the wait instruction is not used to wait until the value of a signal changes, like we saw up to now, but to wait for a given duration. This process models a clock generator. Signal clk is the clock of our system, it is periodic with period 20 ns (50 MHz) and has duty cycle.

Process P2 models a register that, if a rising edge of clk just occurred, assigns the value of its input nc to its output c and then waits for the next value change of clk .

Process P3 models an incrementer that assigns the value of its input c , incremented by one, to its output nc ... with a physical delay of 5 ns. It then waits until the value of its input c changes. This is also new. Up to now we always assigned signals with:

which, for the reasons explained in the previous sections, we can implicitly translate into:

This small digital hardware system could be represented by the following figure:

A synchronous counter

With the introduction of the physical time, and knowing that we also have a symbolic time measured in delta , we now have a two dimensional time that we will denote T+D where T is a physical time measured in nano-seconds and D a number of deltas (with no physical duration).

The complete picture

There is one important aspect of the VHDL simulation that we did not discuss yet: after an execution phase all processes are in suspended state. We informally stated that the scheduler then updates the values of the signals that have been assigned. But, in our example of a synchronous counter, shall it update signals clk , c and nc at the same time? What about the physical delays? And what happens next with all processes in suspended state and none in run-able state?

The complete (but simplified) simulation algorithm is the following:

  • Set current time Tc to 0+0 (0 ns, 0 delta-cycle)
  • Initialize all signals.
  • Record the values and delays of signal assignments.
  • Record the conditions for the process to resume (delay or signal change).
  • The resume time of processes suspended by a wait for <delay> .
  • The next time at which a signal value shall change.
  • Update signals that need to be.
  • Put in run-able state all processes that were waiting for a value change of one of the signals that has been updated.
  • Put in run-able state all processes that were suspended by a wait for <delay> statement and for which the resume time is Tc .
  • If Tn is infinity, stop simulation. Else, start a new simulation cycle.

Manual simulation

To conclude, let us now manually exercise the simplified simulation algorithm on the synchronous counter presented above. We arbitrary decide that, when several processes are run-able, the order will be P3 > P2 > P1 . The following tables represent the evolution of the state of the system during the initialization and the first simulation cycles. Each signal has its own column in which the current value is indicated. When a signal assignment is executed, the scheduled value is appended to the current value, e.g. a/b@T+D if the current value is a and the next value will be b at time T+D (physical time plus delta cycles). The 3 last columns indicate the condition to resume the suspended processes (name of signals that must change or time at which the process shall resume).

Initialization phase:

Operations
Set current time0+0
Initialize all signals0+0'0'00
0+0'0'00/1@5+0
0+0'0'00/1@5+0
0+0'0'00/1@5+0
0+0'0'00/1@5+0
0+0'0'00/1@5+0
0+0'0'/'0'@0+100/1@5+0
0+0'0'/'0'@0+100/1@5+010+0
Compute next time0+00+1'0'/'0'@0+100/1@5+010+0

Simulation cycle #1

Operations
Set current time0+1'0'/'0'@0+100/1@5+010+0
Update signals0+1'0'00/1@5+010+0
Compute next time0+15+0'0'00/1@5+010+0
Note: during the first simulation cycle there is no execution phase because none of our 3 processes has its resume condition satisfied. P2 is waiting for a value change of clk and there has been a transaction on clk , but as the old and new values are the same, this is not a value change .

Simulation cycle #2

Operations
Set current time5+0'0'00/1@5+010+0
Update signals5+0'0'0110+0
Compute next time5+010+0'0'0110+0
Note: again, there is no execution phase. nc changed but no process is waiting on nc .

Simulation cycle #3

Operations
Set current time10+0'0'0110+0
Update signals10+0'0'0110+0
10+0'0'/'1'@10+101
10+0'0'/'1'@10+10120+0
Compute next time10+010+1'0'/'1'@10+10120+0

Simulation cycle #4

Operations
Set current time10+1'0'/'1'@10+10120+0
Update signals10+1'1'0120+0
10+1'1'0120+0
10+1'1'0/1@10+2120+0
10+1'1'0/1@10+2120+0
10+1'1'0/1@10+2120+0
Compute next time10+110+2'1'0/1@10+2120+0

Simulation cycle #5

Operations
Set current time10+2'1'0/1@10+2120+0
Update signals10+2'1'1120+0
10+2'1'11/2@15+020+0
10+2'1'11/2@15+020+0
Compute next time10+215+0'1'11/2@15+020+0
Note: one could think that the nc update would be scheduled at 15+2 , while we scheduled it at 15+0 . When adding a non-zero physical delay (here 5 ns ) to a current time ( 10+2 ), the delta cycles vanish. Indeed, delta cycles are useful only to distinguish different simulation times T+0 , T+1 ... with the same physical time T . As soon as the physical time changes, the delta cycles can be reset.

Simulation cycle #6

Operations
Set current time15+0'1'11/2@15+020+0
Update signals15+0'1'1220+0
Compute next time15+020+0'1'1220+0

Simulation cycle #7

Operations
Set current time20+0'1'1220+0
Update signals20+0'1'1220+0
20+0'1'/'0'@20+112
20+0'1'/'0'@20+11230+0
Compute next time20+020+1'1'/'0'@20+11230+0

Simulation cycle #8

Operations
Set current time20+1'1'/'0'@20+11230+0
Update signals20+1'0'1230+0
20+1'0'1230+0
20+1'0'1230+0
20+1'0'1230+0
Compute next time20+130+0'0'1230+0

Simulation cycle #9

Operations
Set current time30+0'0'1230+0
Update signals30+0'0'1230+0
30+0'0'/'1'@30+112
30+0'0'/'1'@30+11240+0
Compute next time30+030+1'0'/'1'@30+11240+0

Simulation cycle #10

Operations
Set current time30+1'0'/'1'@30+11240+0
Update signals30+1'1'1240+0
30+1'1'1240+0
30+1'1'1/2@30+2240+0
30+1'1'1/2@30+2240+0
30+1'1'1/2@30+2240+0
Compute next time30+130+2'1'1/2@30+2240+0

Simulation cycle #11

Operations
Set current time30+2'1'1/2@30+2240+0
Update signals30+2'1'2240+0
30+2'1'22/3@35+040+0
30+2'1'22/3@35+040+0
Compute next time30+235+0'1'22/3@35+040+0

Got any vhdl Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

VHDL Logical Operators and Signal Assignments for Combinational Logic

In this post, we discuss the VHDL logical operators, when-else statements , with-select statements and instantiation . These basic techniques allow us to model simple digital circuits.

In a previous post in this series, we looked at the way we use the VHDL entity, architecture and library keywords. These are important concepts which provide structure to our code and allow us to define the inputs and outputs of a component.

However, we can't do anything more than define inputs and outputs using this technique. In order to model digital circuits in VHDL, we need to take a closer look at the syntax of the language.

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

Combinational logic is the simplest of the two, consisting primarily 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).

Sequential circuits use a clock and require storage elements such as flip flops . As a result, changes in the output are synchronised to the circuit clock and are not immediate. We talk more specifically about modelling combinational logic in this post, whilst sequential logic is discussed in the next post.

Combinational Logic

The simplest elements to model in VHDL are the basic logic gates – AND, OR, NOR, NAND, NOT and XOR.

Each of these type of gates has a corresponding operator which implements their functionality. Collectively, these are known as logical operators in VHDL.

To demonstrate this concept, let us consider a simple two input AND gate such as that shown below.

The VHDL code shown below uses one of the logical operators to implement this basic circuit.

Although this code is simple, there are a couple of important concepts to consider. The first of these is the VHDL assignment operator (<=) which must be used for all signals. This is roughly equivalent to the = operator in most other programming languages.

In addition to signals, we can also define variables which we use inside of processes. In this case, we would have to use a different assignment operator (:=).

It is not important to understand variables in any detail to model combinational logic but we talk about them in the post on the VHDL process block .

The type of signal used is another important consideration. We talked about the most basic and common VHDL data types in a previous post.

As they represent some quantity or number, types such as real, time or integer are known as scalar types. We can't use the VHDL logical operators with these types and we most commonly use them with std_logic or std_logic_vectors.

Despite these considerations, this code example demonstrates how simple it is to model basic logic gates.

We can change the functionality of this circuit by replacing the AND operator with one of the other VHDL logical operators.

As an example, the VHDL code below models a three input XOR gate.

The NOT operator is slightly different to the other VHDL logical operators as it only has one input. The code snippet below shows the basic syntax for a NOT gate.

  • Mixing VHDL Logical Operators

Combinational logic circuits almost always feature more than one type of gate. As a result of this, VHDL allows us to mix logical operators in order to create models of more complex circuits.

To demonstrate this concept, let’s consider a circuit featuring an AND gate and an OR gate. The circuit diagram below shows this circuit.

The code below shows the implementation of this circuit using VHDL.

This code should be easy to understand as it makes use of the logical operators we have already talked about. However, it is important to use brackets when modelling circuits with multiple logic gates, as shown in the above example. Not only does this ensure that the design works as intended, it also makes the intention of the code easier to understand.

  • Reduction Functions

We can also use the logical operators on vector types in order to reduce them to a single bit. This is a useful feature as we can determine when all the bits in a vector are either 1 or 0.

We commonly do this for counters where we may want to know when the count reaches its maximum or minimum value.

The logical reduction functions were only introduced in VHDL-2008. Therefore, we can not use the logical operators to reduce vector types to a single bit when working with earlier standards.

The code snippet below shows the most common use cases for the VHDL reduction functions.

Mulitplexors in VHDL

In addition to logic gates, we often use multiplexors (mux for short) in combinational digital circuits. In VHDL, there are two different concurrent statements which we can use to model a mux.

The VHDL with select statement, also commonly referred to as selected signal assignment, is one of these constructs.

The other method we can use to concurrently model a mux is the VHDL when else statement.

In addition to this, we can also use a case statement to model a mux in VHDL . However, we talk about this in more detail in a later post as this method also requires us to have an understanding of the VHDL process block .

Let's look at the VHDL concurrent statements we can use to model a mux in more detail.

VHDL With Select Statement

When we use the with select statement in a VHDL design, we can assign different values to a signal based on the value of some other signal in our design.

The with select statement is probably the most intuitive way of modelling a mux in VHDL.

The code snippet below shows the basic syntax for the with select statement in VHDL.

When we use the VHDL with select statement, the <mux_out> field is assigned data based on the value of the <address> field.

When the <address> field is equal to <address1> then the <mux_out> signal is assigned to <a>, for example.

We use the the others clause at the end of the statement to capture instance when the address is a value other than those explicitly listed.

We can exclude the others clause if we explicitly list all of the possible input combinations.

  • With Select Mux Example

Let’s consider a simple four to one multiplexer to give a practical example of the with select statement. The output Q is set to one of the four inputs (A,B, C or D) depending on the value of the addr input signal.

The circuit diagram below shows this circuit.

This circuit is simple to implement using the VHDL with select statement, as shown in the code snippet below.

VHDL When Else Statements

We use the when statement in VHDL to assign different values to a signal based on boolean expressions .

In this case, we actually write a different expression for each of the values which could be assigned to a signal. When one of these conditions evaluates as true, the signal is assigned the value associated with this condition.

The code snippet below shows the basic syntax for the VHDL when else statement.

When we use the when else statement in VHDL, the boolean expression is written after the when keyword. If this condition evaluates as true, then the <mux_out> field is assigned to the value stated before the relevant when keyword.

For example, if the <address> field in the above example is equal to <address1> then the value of <a> is assigned to <mux_out>.

When this condition evaluates as false, the next condition in the sequence is evaluated.

We use the else keyword to separate the different conditions and assignments in our code.

The final else statement captures the instances when the address is a value other than those explicitly listed. We only use this if we haven't explicitly listed all possible combinations of the <address> field.

  • When Else Mux Example

Let’s consider the simple four to one multiplexer again in order to give a practical example of the when else statement in VHDL. The output Q is set to one of the four inputs (A,B, C or D) based on the value of the addr signal. This is exactly the same as the previous example we used for the with select statement.

The VHDL code shown below implements this circuit using the when else statement.

  • Comparison of Mux Modelling Techniques in VHDL

When we write VHDL code, the with select and when else statements perform the same function. In addition, we will get the same synthesis results from both statements in almost all cases.

In a purely technical sense, there is no major advantage to using one over the other. The choice of which one to use is often a purely stylistic choice.

When we use the with select statement, we can only use a single signal to determine which data will get assigned.

This is in contrast to the when else statements which can also include logical descriptors.

This means we can often write more succinct VHDL code by using the when else statement. This is especially true when we need to use a logic circuit to drive the address bits.

Let's consider the circuit shown below as an example.

To model this using a using a with select statement in VHDL, we would need to write code which specifically models the AND gate.

We must then include the output of this code in the with select statement which models the multiplexer.

The code snippet below shows this implementation.

Although this code would function as needed, using a when else statement would give us more succinct code. Whilst this will have no impact on the way the device works, it is good practice to write clear code. This help to make the design more maintainable for anyone who has to modify it in the future.

The VHDL code snippet below shows the same circuit implemented with a when else statement.

Instantiating Components in VHDL

Up until this point, we have shown how we can use the VHDL language to describe the behavior of circuits.

However, we can also connect a number of previously defined VHDL entity architecture pairs in order to build a more complex circuit.

This is similar to connecting electronic components in a physical circuit.

There are two methods we can use for this in VHDL – component instantiation and direct entity instantiation .

  • VHDL Component Instantiation

When using component instantiation in VHDL, we must define a component before it is used.

We can either do this before the main code, in the same way we would declare a signal, or in a separate package.

VHDL packages are similar to headers or libraries in other programming languages and we discuss these in a later post.

When writing VHDL, we declare a component using the syntax shown below. The component name and the ports must match the names in the original entity.

After declaring our component, we can instantiate it within an architecture using the syntax shown below. The <instance_name> must be unique for every instantiation within an architecture.

In VHDL, we use a port map to connect the ports of our component to signals in our architecture.

The signals which we use in our VHDL port map, such as <signal_name1> in the example above, must be declared before they can be used.

As VHDL is a strongly typed language, the signals we use in the port map must also match the type of the port they connect to.

When we write VHDL code, we may also wish to leave some ports unconnected.

For example, we may have a component which models the behaviour of a JK flip flop . However, we only need to use the inverted output in our design meaning. Therefore, we do not want to connect the non-inverted output to a signal in our architecture.

We can use the open keyword to indicate that we don't make a connection to one of the ports.

However, we can only use the open VHDL keyword for outputs.

If we attempt to leave inputs to our components open, our VHDL compiler will raise an error.

  • VHDL Direct Entity Instantiation

The second instantiation technique is known as direct entity instantiation.

Using this method we can directly connect the entity in a new design without declaring a component first.

The code snippet below shows how we use direct entity instantiation in VHDL.

As with the component instantiation technique, <instance_name> must be unique for each instantiation in an architecture.

There are two extra requirements for this type of instantiation. We must explicitly state the name of both the library and the architecture which we want to use. This is shown in the example above by the <library_name> and <architecture_name> labels.

Once the component is instantiated within a VHDL architecture, we use a port map to connect signals to the ports. We use the VHDL port map in the same way for both direct entity and component instantiation.

Which types can not be used with the VHDL logical operators?

Scalar types such as integer and real.

Write the code for a 4 input NAND gate

We can use two different types of statement to model multiplexors in VHDL, what are they?

The with select statement and the when else statement

Write the code for an 8 input multiplexor using both types of statement

Write the code to instantiate a two input AND component using both direct entity and component instantiation. Assume that the AND gate is compiled in the work library and the architecture is named rtl.

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.

VHDLwhiz

How a signal is different from a variable in VHDL

In the previous tutorial we learned how to declare a variable in a process. Variables are good for creating algorithms within a process, but they are not accessible to the outside world. If a scope of a variable is only within a single process, how can it interact with any other logic? The solution for this is a signal .

Signals are declared between the architecture <architecture_name> of <entity_name> is line and the begin statements in the VHDL file. This is called the declarative part of the architecture.

This blog post is part of the Basic VHDL Tutorials series.

The syntax for declaring a signal is:

A signal may optionally be declared with an initial value:

In this video tutorial we learn how to declare a signal. We will also learn the main difference between a variable and a signal:

The final code we created in this tutorial:

The output to the simulator console when we pressed the run button in ModelSim:

Let me send you a Zip with everything you need to get started in 30 seconds

Unsubscribe at any time

We created a signal and a variable with the same initial value of 0. In our process we treated them in the exact same way, yet the printouts reveal that they behaved differently. First we saw that the assignment to a variable and a signal has a different notation in VHDL. Variable assignment uses the := operator while signal assignment uses the <= operator.

MyVariable behaves as one would expect a variable to behave. In the first iteration of the loop it is incremented to 1, and then to 2. The last printout from the first iteration shows that its value is still 2, as we would expect.

MySignal behaves slightly different. The first +1 increment doesn’t seem to have any effect. The printout reveals that its value is still 0, the initial value. The same is true after the second +1 increment. Now the value of MyVariable is 2, but the value of MySignal is still 0. After wait for 10 ns; the third printout shows that the value of MySignal is now 1. The subsequent printouts follow this pattern as well.

What is this sorcery? I will give you a clue, the wait for 10 ns; has something to do with it. Signals are only updated when a process is paused. Our process pauses only one place, at wait for 10 ns; . Therefore, the signal value changes only every time this line is hit. The 10 nanoseconds is an arbitrary value, it could be anything, even 0 nanoseconds. Try it!

Another important observation is that event though the signal was incremented twice before the wait , its value only incremented once. This is because when assigning to a signal in a process, the last assignment “wins”. The <= operator only schedules a new value onto the signal, it doesn’t change until the wait . Therefore, at the second increment of MySignal , 1 is added to its old value. When it is incremented again, the first increment is completely lost.

Get free access to the Basic VHDL Course

Download the course material and get started.

You will receive a Zip with exercises for the 23 video lessons as VHDL files where you fill in the blanks, code answers, and a link to the course.

By submitting, you consent to receive marketing emails from VHDLwhiz (unsubscribe anytime).

  • A variable can be used within one process while signals have a broader scope
  • Variable assignment is effective immediately while signals are updated only when a process pauses
  • If a signal is assigned to several times without a wait , the last assignment “wins”

Go to the next tutorial »

' src=

I’m from Norway, but I live in Bangkok, Thailand. Before I started VHDLwhiz, I worked as an FPGA engineer in the defense industry. I earned my master’s degree in informatics at the University of Oslo.

Similar Posts

How to create a signal vector in VHDL: std_logic_vector

How to create a signal vector in VHDL: std_logic_vector

The std_logic_vector type can be used for creating signal buses in VHDL. The std_logic is the most commonly used type in VHDL, and the std_logic_vector is the array version of it. While the std_logic is great for modeling the value that can be carried by a single wire, it’s not very practical for implementing collections…

What is VHDL?

What is VHDL?

In short, VHDL is a computer language used for designing digital circuits. I use the term “computer language” to distinguish VHDL from other, more common programming languages like Java or C++. But is VHDL a programming language? Yes, it is. It’s a programming language that is of no use when it comes to creating computer…

Generate statement debouncer example

Generate statement debouncer example

The generate statement in VHDL can automatically duplicate a block of code to closures with identical signals, processes, and instances. It’s a for loop for the architecture region that can create chained processes or module instances.

How to use Wait On and Wait Until in VHDL

How to use Wait On and Wait Until in VHDL

In the previous tutorial we learned the main differences between signals and variables. We learned that signals have a broader scope than variables, which are only accessible within one process. So how can we use signals for communication between several processes? We have already learned to use wait; to wait infinitely, and wait for to…

Make Lattice iCEcube2 work on Ubuntu 20.04 and program the iCEstick FPGA board

Make Lattice iCEcube2 work on Ubuntu 20.04 and program the iCEstick FPGA board

This tutorial shows how to install the Lattice iCEcube2 FPGA design software on Ubuntu 20.04. Instead of the Lattice Diamond Programmer, we will use the alternative programmer from Project IceStorm that works flawlessly on Ubuntu Linux. The Lattice iCEcube2 FPGA design software only works on Red Hat-based Linux distributions out of the box. Fortunately, we…

How to check if a vector is all zeros or ones

How to check if a vector is all zeros or ones

I know that I have googled this at least a hundred times throughout my career as an FPGA engineer; how to check if all bits in a std_logic_vector signal are ‘0’ or ‘1’. Of course, you know a few ways to do it already, but you want to find the most elegant code that will…

Leave a Reply Cancel reply

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

Notify me of replies to my comment via email

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Pitfall with mixing of blocking and non-blocking assignments for the same logic/reg in SystemVerilog

VHDL has a clear distinction between signals and variables. Variables are always updated as soon as we assign a value to them. However, a signal is only updated at the end of the process block.

In Verilog and SystemVerilog there is no distinction like variable and signal found in the VHDL. However, here we have the concept of blocking and non-blocking assignment. The non-blocking assignment behaves like the variable in VHDL while the blocking assignment behaves like the signal in VHDL. Atleast this is my conclusion.

Now the issue is that, it is allowed to mix blocking and non-blocking assignment for the same reg or logic type in Verilog/SystemVerilog. This brings me to my question (about synthesizeable code):

I assume that mixing blocking and non-blocking assignments for synthesis code for the same reg or logic type, is a bad idea. Why is it allowed in the language?
How does one make sure that mixing of blocking and non-blocking assignment for the same reg or logic type does not happen (by mistake)?
Is it a good practice to have blocks of code that combine reg or logic types like we can have signal and variable in the same VHDL process?

Note: This question is not asking about difference between the blocking and non-blocking assignments

  • system-verilog

quantum231's user avatar

  • \$\begingroup\$ How does one make sure that mixing of blocking and non-blocking assignment for the same reg or logic type does not happen (by mistake)? " -- A good designer doesn't mix it. As simple as that. However linting tools can catch this, not sure about RTL compilers or synthesisers. \$\endgroup\$ –  Mitu Raj Commented Feb 25, 2022 at 18:00
  • \$\begingroup\$ A good designer may not mix them on purpose, its just = vs <=, very easy to mix up if a code block is using both of them anyway \$\endgroup\$ –  quantum231 Commented Feb 25, 2022 at 18:38

Verilog and SystemVerilog can also be used for simulation and it currently supports way more than what can be synthesized. And mixing them in simulations works ok.

You will get a synthesis error if you do that, so eventually you will stop doing it. Also, the syntax is quite different = vs <=

As far as I know reg can always be replaced by logic in SystemVerilog. In fact, you will only not use logic (and explicitly specify that the variable is a reg or wire ) when you have multiple drivers for a net, then you should use wire and deal with the multiple drivers explicitly.

jDAQ's user avatar

  • \$\begingroup\$ The last sentence does not make sense "In fact, you will only not use logic when you have multiple drivers for a net, then you should use wire." \$\endgroup\$ –  quantum231 Commented Feb 24, 2022 at 10:56
  • \$\begingroup\$ I updated that phrase, also here are some other resources stackoverflow.com/questions/13282066/… electronics.stackexchange.com/questions/331393/… . logic was introduced only in SV while reg and wire already existed in Verilog. I don't know any situation where a reg type cannot be changed to logic , almost the same holds for wire , except that logic cannot be driven by multiple drivers, for that you have to explicitly declare it as wire \$\endgroup\$ –  jDAQ Commented Feb 24, 2022 at 15:41

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged vhdl system-verilog or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • We spent a sprint addressing your requests — here’s how it went

Hot Network Questions

  • Joint brokerage account legalities re: dividend, stock losses
  • Would it be moral for Danish resitance in WW2 to kill collaborators?
  • Decorate equations with arrows using TikZ
  • Why are responses to an attack in a cycling race immediate?
  • Why bother with planetary battlefields?
  • Everything has a tiny nuclear reactor in it. How much of a concern are illegal nuclear bombs?
  • Is "sinnate" a word? What does it mean?
  • How does a country without exit immigration check know you have overstayed?
  • Who is the woman who speaks when the Ravagers stop the Benatar?
  • In a sum of high-variance lognormals, what fraction comes from the first term?
  • Directions of puff pastry folds
  • Any alternative to lockdown browser?
  • Why is there not a test for diagonalizability of a matrix
  • Using 50 Ω coax cable instead of passive probe
  • When is bribery legal?
  • LilyPond: how do I visualize Bezier control points?
  • What is gñânendriyas?
  • Equivalence of omniscience principles for natural numbers and analytic omniscience principles for Cauchy real numbers
  • How can I power both sides of breaker box with two 120 volt battery backups?
  • Why did Nigel Farage choose Clacton as the constituency to campaign in?
  • Filling the areas enclosed by two curves and calculate them
  • Minimum number of select-all/copy/paste steps for a string containing n copies of the original
  • ForeignFunctionLoad / RawMemoryAllocate and c-struct that includes an array
  • Does closedness of the image of unit sphere imply the closed range of the operator

what is variable assignment in vhdl

Type recast on assignment

I did recently stumble upon strange error what made me rethink all about Python type assignment. The code in question declared loop iteration variable and then incremented it with counter+=valuearray_uint8[index] It turned out that for Miniforge aarch64 such statement did change left side type to uint8 while LTS 20.04 Python from apt behaved ok. This brings on interesting question for reassignment. Knowing that all Python values derive from PyObject common class is most certainly possible to reassign types. The main question is when was such behaviour decided? For sure if you assign incompatible types then either recast or exception are two ways to handle issue and it should be selectable with compiler argument e.g. --strict. For numbers where type conversion is possible for example moving between int lengths interpreter should just convert result to corresponding left size type before assignment but never change left hand type.

Do you have a code example for reproducing this? Ideally with a link to mypy/pyright playgrounds. Also, which type checker were you using? Is it possible the difference you saw was because of missing stubs and hence defaulting to Any in one of the versions?

Included is test script i used and also printout that shows same results for

  • IMX8 aarch64 24.04 LTS and deadsnake Python 10
  • MACOS miniconda and native Python It seems to consistently get results from result of calculation and then reassign types when needed. Also it came to me that numpy and ctypes are not python native and if something is strange then these originate from respective packages. For native case when one argument is float then result is recast to float. Of course such behaviour can be overridden with explicit type conversions but given that there is no memory or speed gain in using smaller data values then it is safer to stick to native python types. It can also slip under radar if loop exit result fits in small type, for uint8_t case is smaller than 255.

Script run results (script is included):

I did not find include link so here is the recast.py script

For numpy there seems to be nice solution how to modify existing code with minimal changes. Although variable does not have value attribute as ctypes it has tolist() what does the same - returns value as single integer. We can just add it to where variable in uint8 format is used and all should be ok.

Thanks for response. Here is where i lack knowledge and do not know even what stubs mean. I come from Verilog / VHDL / C / C++ background where calculations never change declared variable type. I know it can be done in Python for exampleyou can start frominteger and reassign to string. Myself have never used such smaller types because these provide no benefit except for ctypes/structure when accessing shared mapped memory from /dev/mem through pointer from Python c module. Now there is task where system architect writes code in Python and I have to take it to NXP LA9310 VSPA dsp. Here is the first time i noticed it when model ends up in infinite loop because of loop counter overflow.

Related Topics

Topic Replies Views Activity
Python Help 0 570 November 29, 2022
Typing 22 1205 November 3, 2023
Ideas 16 1361 April 26, 2023
Ideas 26 2154 November 22, 2023
Python Help 10 607 December 4, 2022
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to assign a value to a variable in a Django template?

e.g., given this template:

While testing it, it would be useful to define the value of the variable without touching the python code that invokes this template. So I'm looking for something like this

Does something like this exist in Django?

  • django-templates

Rob Bednark's user avatar

9 Answers 9

You can use the with template tag.

John's user avatar

  • 64 but can you change the variable's value in the with? –  David 天宇 Wong Commented Feb 16, 2014 at 10:31
  • 4 It seems you cannot declare a container (I've tried list and tuple) in a with clause –  Vladislav Ivanishin Commented Mar 18, 2015 at 1:58
  • 1 If you need to declare a list, use make_list. docs.djangoproject.com/en/1.9/ref/templates/builtins/#make-list –  MrValdez Commented Jul 1, 2016 at 7:55
  • 4 Jinja says it's {% set myvar=value %} why it doesn't work in django? –  holms Commented Mar 10, 2018 at 1:08
  • 15 @holms Because Django doesn't use Jinja :-) docs.djangoproject.com/en/1.7/topics/templates –  elimisteve Commented May 12, 2018 at 0:04

Create a template tag:

The app should contain a templatetags directory, at the same level as models.py , views.py , etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Create a file named define_action.py inside of the templatetags directory with the following code:

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.

Then in your template you can assign values to the context like this:

John R Perry's user avatar

  • 4 in my case after loop this returns old value :( –  holms Commented Mar 13, 2018 at 9:46
  • 8 In the latest version it appears that you can use simple_tag instead of assignment_tag (and it worked for me). –  Katharine Osborne Commented Mar 13, 2018 at 19:44
  • Issue I got with this solution is that it appears, that you cannot override values. –  Jakub Jabłoński Commented Mar 13, 2020 at 15:57
  • 1 if you want to use this technique to set a list instead of just a value, check this: stackoverflow.com/a/34407158/2193235 –  msb Commented Jun 13, 2020 at 1:45
  • 2 if you are setting the variable as an integer and you want to increment it (for example), you need to use add : {% define counter|add:1 as counter %} . Similarly for other operations. –  msb Commented Jun 13, 2020 at 1:47

An alternative way that doesn't require that you put everything in the "with" block is to create a custom tag that adds a new variable to the context. As in:

This will allow you to write something like this in your template:

Note that most of this was taken from here

Lundis's user avatar

  • How about assigning variables to other variables present in the context? And on a different note: allowing templates to arbitrarily assign context variables without checking if they exist already may have security implications. A more sensible approach in my opinion would be to check the context for the variable before attempting to assign it: –  user656208 Commented Aug 7, 2015 at 11:49
  • if context.get(self.var_name): raise SuspiciousOperation("Attempt to assign variable from template already present in context") –  user656208 Commented Aug 7, 2015 at 11:50

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates ). Because of this, the recommended way to change any variable is via touching the Python code.

djvg's user avatar

  • 8 Thanks for the pointer. From a perspective of a designer is it sometimes easier to quickly set a variable to test various states of a page while designing it. Not suggesting this practice to be used in a running code. –  Alexis Commented Jul 1, 2009 at 22:21
  • 3 the "with" tag is accepted in django1.0. So looks like they are finally amending their philosophy :). –  Evgeny Commented Dec 20, 2009 at 19:35
  • 4 As a matter of facts, the "with" tag is just for aliases. This may have a huge impact on performance (and on readability as well!) but it is not really setting a variable in traditional programming terms. –  rob Commented Dec 20, 2009 at 23:48

The best solution for this is to write a custom assignment_tag . This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

Start by creating a template tag file (eg. appname/templatetags/hello_world.py ):

Now you may use the get_addressee template tag in your templates:

Mr. Lance E Sloan's user avatar

  • 6 For folks using the newer Django versions, its called simple_tag now! Save the time to figure out why "register.." is not recognized in your code... –  kaya Commented Sep 1, 2018 at 9:25

Perhaps the default template filter wasn't an option back in 2009...

John Mee's user avatar

  • I must say that this is what I was looking! It can be also be used with with : {% with state=form.state.value|default:other_context_variable %} instead of other_context_variable we can also use any 'string_value' as well –  Saurav Kumar Commented Feb 7, 2018 at 9:48
  • But it will print it, and I need to save it for later use –  holms Commented Mar 10, 2018 at 1:18

Use the with statement .

I can't imply the code in first paragraph in this answer . Maybe the template language had deprecated the old format.

ramwin's user avatar

This is not a good idea in general. Do all the logic in python and pass the data to template for displaying. Template should be as simple as possible to ensure those working on the design can focus on design rather than worry about the logic.

To give an example, if you need some derived information within a template, it is better to get it into a variable in the python code and then pass it along to the template.

Sarang's user avatar

In your template you can do like this:

In your template-tags you can add a tag like this:

Ashish Gupta's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged django django-templates or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Do you always experience the gravitational influence of other mass as you see them in your frame?
  • Decorate equations with arrows using TikZ
  • Are there dedicated research facilities in the USA?
  • If the alien nest was under the primary heat exchangers, why didn't the marines just blow them up or turn them off so they freeze?
  • What does going "alive into Sheol" mean in Numbers 16?
  • How can I power both sides of breaker box with two 120 volt battery backups?
  • Why does black have a higher win rate here?
  • Why are Probability Generating Functions important?
  • Hereditarily countable sets in Antifounded ZF
  • Is "necesse est tibi esse placidus" valid classical Latin?
  • Would it be moral for Danish resitance in WW2 to kill collaborators?
  • Transferring at JFK: How is passport checked if flights arrive at/depart from adjacent gates?
  • When is bribery legal?
  • Two Sinus Multiply and Add
  • Why the number of bits or bytes is different for a folder that has been copied between two external drives?
  • What caused the builder to change plans midstream on this 1905 library in New England?
  • How do we define addition?
  • Can a country refuse to deliver a person accused of attempted murder?
  • Plastic plugs used to fasten cover over radiator
  • Subscripts in fractions on an exponent look terrible
  • Where can I find a complete archive of audio recordings of Hitler speeches?
  • Using 50 Ω coax cable instead of passive probe
  • Can I access Apple ID setting in mac by terminal, how?
  • What makes Python better suited to quant finance than Matlab / Octave, Julia, R and others?

what is variable assignment in vhdl

IMAGES

  1. Using variables for registers or memory in VHDL

    what is variable assignment in vhdl

  2. PPT

    what is variable assignment in vhdl

  3. VHDL types

    what is variable assignment in vhdl

  4. VHDL Introduction

    what is variable assignment in vhdl

  5. 😀 Vhdl assignment. Vhdl overload assignment operator. 2019-03-06

    what is variable assignment in vhdl

  6. PPT

    what is variable assignment in vhdl

VIDEO

  1. VHDL Operators

  2. Arrays & Array assignment || Verilog lectures in Telugu

  3. _DSDV_Discuss Structure, Variable Assignment Statement in verilog

  4. variable and assignment #learnngrow #coding #coder

  5. 6 storing values in variable, assignment statement

  6. [Algorithm Session 01]

COMMENTS

  1. what exactly is a variable in VHDL?

    For your specific code, yes, the variable var will cause a flip flop to be synthesized. It would also do the exact same thing if 'var' was a signal and the output <= var; assignment was outside of the process. In your code, var is set based on the sole assignment to refer to the Dout wire of a clocked element (flip flop) that has a Din of input ...

  2. Variables vs. Signals in VHDL

    Variables and Signals in VHDL appears to be very similar. They can both be used to hold any type of data assigned to them. The most obvious difference is that variables use the := assignment symbol whereas signals use the <= assignment symbol. However the differences are more significant than this and must be clearly understood to know when to ...

  3. Variables

    Variables and signals show a fundamentally different behavior. In a process, the last signal assignment to a signal is carried out when the process execution is suspended. Value assignments to variables, however, are carried out immediately. To distinguish between a signal and a variable assignment different symbols are used: '⇐ ...

  4. Variable

    Variables - VHDL Example. Variables in VHDL act similarly to variables in C. Their value is valid at the exact location in the code where the variable is modified. Therefore, if a signal uses the value of the variable before the assignment, it will have the old variable value. If a signal uses the value of the variable after the assignment it ...

  5. Assignment Symbol

    In VHDL there are two assignment symbols: <= Assignment of Signals. := Assignment of Variables and Signal Initialization. Either of these assignment statements can be said out loud as the word "gets". So for example in the assignment: test <= input_1; You could say out loud, "The signal test gets (assigned the value from) input_1.".

  6. The Variable: A Valuable Object in Sequential VHDL

    This description uses sequential statements. The connection between the process black box and the outside world is achieved through the signals. The process may read the value of these signals or assign a value to them. So VHDL uses signals to connect the sequential part of the code to the concurrent domain.

  7. VHDL Reference Guide

    A variable assignment may not be given a delay. A variable in a process can act as a register, if it is read before it has been written to, since it retains its value between sucessive process activations. process (CLK) variable Q : std_ulogic; begin. if CLK'event and CLK='1' then. PULSE <= D and not(Q); Q := D; -- PULSE and Q act as registers.

  8. PDF VHDL Syntax Reference

    Variables are objects used to store intermediate values between sequential VHDL statements. Variables are only allowed in processes, procedures and functions, and they are always local to those functions. When a value is assigned to a variable, ":=" is used. Example: signal Grant, Select: std_logic; process(Rst, Clk) variable Q1, Q2, Q3 ...

  9. VHDL Tutorial

    A variable behaves like you would expect in a software programming language, which is much different than the behavior of a signal. Although variables represent data like the signal, they do not have or cause events and are modified differently. Variables are modified with the variable assignment. For example, a:=b; assigns the value of b to a.

  10. PDF 6. Sequential and Concurrent Statements in The Vhdl Language

    A VHDL description has two domains: a sequential domain and a concurrent domain. The sequential domain is represented by a process or subprogram that contains sequential statements. These statements are exe- ... variable assignment, if statement, case statement, loop statements (loop, while loop, for, next,

  11. VHDL Reference Guide

    In VHDL-93, shared variables may be declared within an architecture, block, generate statement, or package: shared variable variable_name : type; Shared variables may be accessed by more than one process. However, the language does not define what happens if two or more processes make conflicting accesses to a shared variable at the same time.

  12. VHDL Online Help

    The variable assignment statement modifies the value of the variable. The new value of the variable is obtained by assigning an expression to this variable. In order to distinguish variable assignment from signal assignment, the variable assignment symbol is different (:=). The expression assigned to a variable must give results of the same ...

  13. vhdl Tutorial => Signals vs. variables, a brief overview of the

    VHDL also uses variables and they have exactly the same role as in most imperative languages. But VHDL also offers another kind of value container: the signal. Signals also store values, can also be assigned and read. The type of values that can be stored in signals is (almost) the same as in variables.

  14. VHDL Variable Vs. Signal

    With the VHDL-2000/2002 update, shared variables are not permitted to be used with regular types. Instead they may only be used with protected types. Protected types do not allow assignment. Hence, the shared variable is much more like a handle to the object than it is a variable. -

  15. VHDL Logical Operators and Signal Assignments for Combinational Logic

    The VHDL code shown below uses one of the logical operators to implement this basic circuit. and_out <= a and b; Although this code is simple, there are a couple of important concepts to consider. The first of these is the VHDL assignment operator (<=) which must be used for all signals.

  16. Difference between Blocking and Non-Blocking assignment in VHDL

    But it's worth understanding how this timing model works - I'd say it's absolutely key to understanding VHDL. Grasp this and VHDL will become a lot easier. It relies on 2 key points: There are only variable assignments and signal assignments, the latter are also known as postponed assignments.

  17. Variables in VHDL

    1. When you declare a variable inside a process in VHDL, if you also initialise it to a certain value, i.e. a 0 or a 1, does this variable's value from previous iterations get 're-initialised' to the value you have given it? For example every time this process is enabled by the change in the 10MHz clock, does the variable shift be initialised ...

  18. How a signal is different from a variable in VHDL

    First we saw that the assignment to a variable and a signal has a different notation in VHDL. Variable assignment uses the := operator while signal assignment uses the <= operator. MyVariable behaves as one would expect a variable to behave. In the first iteration of the loop it is incremented to 1, and then to 2.

  19. vhdl

    The non-blocking assignment behaves like the variable in VHDL while the blocking assignment behaves like the signal in VHDL. Atleast this is my conclusion. Now the issue is that, it is allowed to mix blocking and non-blocking assignment for the same reg or logic type in Verilog/SystemVerilog. This brings me to my question (about synthesizeable ...

  20. Type recast on assignment

    The code in question declared loop iteration variable and then incremented it with counter+=valuearray_uint8[index] It turned out that for Miniforge aarch64 such statement did change left side type to uint8 while LTS 20.04 Python from apt behaved ok. ... # check variable type recast during assignment import numpy as np import ctypes as ct X1 ...

  21. vhdl

    variable abs_n : signed(31 downto 0) := abs(n); is initialising the variable abs_n once at the beginning of the simulation (technically during elaboration). At this time, the signal n will have the value 'U' and abs('U') will be 'X', so the variable abs_n is initialised with the value 'X' and never assigned any value after that. So, instead of:

  22. Assign values to an array partially in VHDL?

    1. I have an array in VHDL of the form, type CacheArray is array(0 to 15) of std_logic_vector(33 downto 0); signal cache_array: CacheArray := (others => (others => '0')); I wish to assign values to this array such that only one bit of each index is initialized. I suspected something like this will work,

  23. How to assign a value to a variable in a Django template?

    Create a template tag: The app should contain a templatetags directory, at the same level as models.py, views.py, etc.If this doesn't already exist, create it - don't forget the __init__.py file to ensure the directory is treated as a Python package.. Create a file named define_action.py inside of the templatetags directory with the following code: ...