So in my earlier posts, I explained how to design an ALU using VHDL. And today we will see how to implement it in VERILOG with arithmetic, relational and shift operators.

So we will start with the code:

module ALU_FPGA(z,a,b,sel);
input [3:0]a,b;
input [2:0]sel;    //3 bit select line for the operation
output reg [4:0]z;

always @(sel,a,b)  //behavioral modeling
begin
case(sel)
4’b000:z=a+b;    //if sel=0,add a and b
4’b001:z=a-b;    //if sel=1,subtract a and b
4’b010:z=a+1;   //if sel=2,increment a
4’b011:z=a-1;    //if sel=3,decrement a
4’b100:z=a&&b;   //if sel=4,AND a and b
4’b101:z=a||b;    //if sel=5,OR a and b
4’b110:z=a<<1;    //if sel=6, Shift a left by 1 bit
4’b111:z=a>>1;    //if sel=7,Shift a right by 1 bit
endcase
end

endmodule

RTL SCHEMATIC:

TEST BENCH:

initial begin

// Initialize Inputs

a = 4;

b = 3;

sel = 0;

// Wait 100 ns for global reset to finish

#100;

// Add stimulus here

a = 4;

b = 3;

sel = 1;

// Wait 100 ns for global reset to finish

#100;

a = 4;

b = 3;

sel = 2;

// Wait 100 ns for global reset to finish

#100;

a = 4;

b = 3;

sel = 3;

// Wait 100 ns for global reset to finish

#100;

a = 4;

b = 3;

sel = 4;

// Wait 100 ns for global reset to finish

#100;

a = 4;

b = 3;

sel = 5;

// Wait 100 ns for global reset to finish

#100;a = 4;

b = 3;

sel = 6;

// Wait 100 ns for global reset to finish

#100;a = 4;

b = 3;

sel = 7;

// Wait 100 ns for global reset to finish

#100;

end

endmodule

OUTPUT: