...
Ishaan
Posted on 16 Aug 2023

if-else Statement in Verilog

Like C/C++ or any other programming languages, Verilog has if-else keywords which we can use to describe a hardware or use it in verifying the hardware. First, we'll see how to use this to describe a hardware.

Usage

We can use if-else statement to describe a combinational circuit, finite state machine, and testing a circuit. There are few thing we should remember about it.

  1. It is used inside the procedural block(always or initial block). Let us remind, the output of the Verilog module must be reg type if output is generated from procedural block no matter if it is a combinational circuit or sequential circuit.
  2. If there is only one statement for if-else, you can directly write the code and nothing to worry about. If there are multiple statement for if-else statement, the entire if-else statement must be enclosed within begin and end keyword.

Let us describe a hardware to better understand if-else statment in Verilog. The basic building block of the digital circuit is logic gate. Let us describe a simple logic gate, NOT gate using if-else statement.

NOT Gate

NOT gate has one input and one output. The output is complement of the input or if input is 1, output is 0 and if input is 0 output is 1. Let's write verilog code for this.

module not_gate(
    input a,
    output reg y
    );

always @(*)begin
    if(a)
        y = 0;
    else
        y = 1;
end

endmodule

You can make other logic gates using if-else statement.

Ex-OR Gate

Let's write Verilog code for Ex-Or gate using if-else statement. We know that it has two input and one output. If one of the input is 0, output is same as the other input. If one of the input is 1, output is the complement of other input. Let's write Verilog code for this.

module xor_gate(
    input a,b,
    output reg y
    );

always @(*)begin
    if(a)
        y = ~a;
    else
        y = a;
end

endmodule

Multiplexer

We can create combinational circuit using if-else statement. Multiplexer is the most common used circuit in digital system. Let's start with 2X1 MUX which has three inputs, one is select line and other two are inputs selected by the output based on the select line input. if select line is 0, one of the input is selected else other input is selected by the output. Let's write Verilog code for this.

module mux_2x1(
    input i0,i0,s,
    output reg y
    );

always @(*)begin
    if(s)
        y = i1;
    else
        y = i0;
end

endmodule

You can use if-else statement in Verilog HDL to describe a hardware. You can describe logic gates and combinational circuit using it. You can also use this for creating sequential circuit like finite state machine. We'll learn more about this is upcoming articles.

Learn Verilog HDL

Click like if you found this useful

Add Comment

* Required information
1000

Comments

No comments yet. Be the first!