Welcome to another edition of our Verilog series! In this blog post, we’ll explore the implementation of an Arithmetic Logic Unit (ALU) in Verilog. An ALU is a fundamental component of digital systems that performs arithmetic and logical operations on binary data.
It is widely used in processors, microcontrollers, and digital signal processing systems.
Below is the Verilog code for a simple 4-bit ALU, implemented using a Behavioral Modeling approach:
In the behavioral modeling approach, we use a case statement to select different operations based on a control signal.
module alu(
input [3:0] A, B,
input [2:0] sel,
output reg [3:0] result,
output reg carry
);
always @(*)
begin
case(sel)
3'b000: {carry, result} = A + B; // Addition
3'b001: {carry, result} = A - B; // Subtraction
3'b010: result = A & B; // AND
3'b011: result = A | B; // OR
3'b100: result = A ^ B; // XOR
3'b101: result = ~A; // NOT
3'b110: result = A << 1; // Shift Left
3'b111: result = A >> 1; // Shift Right
default: result = 4'b0000;
endcase
end
endmodule
๐งช Testbench
module tb_top;
reg [3:0] A, B;
reg [2:0] sel;
wire [3:0] result;
wire carry;
alu uut(A, B, sel, result, carry);
initial begin
$monitor("Time=%0t A=%b B=%b sel=%b result=%b carry=%b",
$time, A, B, sel, result, carry);
A = 4'b0101; B = 4'b0011;
sel = 3'b000; #10; // Add
sel = 3'b001; #10; // Sub
sel = 3'b010; #10; // AND
sel = 3'b011; #10; // OR
sel = 3'b100; #10; // XOR
sel = 3'b101; #10; // NOT
sel = 3'b110; #10; // Shift Left
sel = 3'b111; #10; // Shift Right
#10 $finish;
end
endmodule
Explanation:
- The ALU performs different operations based on the control signal
sel. - Arithmetic operations include addition and subtraction.
- Logical operations include AND, OR, XOR, and NOT.
- Shift operations move bits left or right.
- The
carryoutput is used for arithmetic operations.
Conclusion
This Verilog implementation of an ALU demonstrates how multiple operations can be integrated into a single module. It is a key building block in processors and digital systems.
What’s Next?
Try extending this ALU by adding more operations or increasing bit width. In the next post, we’ll explore more advanced digital designs and their Verilog implementations.
Happy Coding! ๐
No comments:
Post a Comment